javascript - 为什么空数组上的 findIndex 不返回 -1?
问题描述
我试图在以下程序中只显示一次警报:
const errorToBeShownOnce = [];
export const anExampleOfAFunction = () => {
const num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
} catch (err) {
if (errorToBeShownOnce.findIndex(err.message) === -1) {
alert(err.name, err.message);
errorToBeShownOnce.push(err.message);
console.log("table in if: " + errorToBeShownOnce)
} else {
return
}
} finally {
console.log("final action");
}
};
export const functionToShowErrorMessage = () => {
setInterval(anExampleOfAFunction, 10000);
};
我认为errorToBeShownOnce.findIndex(err.message)
应该相等-1
,因为数组中最初没有数据,但看起来没有。我想了解这里的问题是什么?我不能findIndex
在空数组上使用吗?有人可以帮我处理这个案子吗?
解决方案
Array.prototype.findIndex()
接受回调作为参数,而不是string
. 所以我想如果你真的想findIndex
检查你是否早先显示了那个错误信息,你可以做这样的事情:
const errorMessage = 'randomError';
const errorToBeShownOnce = [];
const result = errorToBeShownOnce.findIndex(e => e === errorMessage);
console.log(result);
如您所见,result
将-1
在这种情况下。
从文档中:
findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。否则,它返回 -1,表示没有元素通过测试。
或者按照建议,Array.prototype.indexOf()
如果您有字符串,则可以使用,如下所示:
const errorMessage = 'randomError';
const errorToBeShownOnce = [];
const result = errorToBeShownOnce.indexOf(errorMessage);
console.log(result);
从文档中:
indexOf() 方法返回可以在数组中找到给定元素的第一个索引,如果不存在则返回 -1。
我希望这有帮助!
推荐阅读
- operating-system - 如何在内核中实现内存管理?
- spring-boot - Postgresql 中突然 100% 的 CPU 使用率
- ubuntu - 如何在 Ubuntu 上将 openssl 添加到 qt 项目?
- c# - 数组变量如何在不使用 C# 中的 new 关键字初始化变量的情况下填充值?
- hdl - 在 Bluespec SV 中为向量结构赋值
- winapi - GetMenuBarInfo() win32 函数
- javascript - 在文件夹中的文件上循环我的 javascript 逻辑
- javascript - 一些 php,sql,js 机制
- windows - 用于自定义 Vsphere Hypervisor 中配置的 VM 的 Terraform
- typescript - 何时在 Typescript 中使用类型约束?