首页 > 解决方案 > 为什么空数组上的 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在空数组上使用吗?有人可以帮我处理这个案子吗?

标签: javascript

解决方案


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。

我希望这有帮助!


推荐阅读