最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

这是JS array.find的错误用法还是要忽略的VSCode警告?

IT培训 admin 1浏览 0评论

这是JS array.find的错误用法还是要忽略的VSCode警告?

我需要用另一个对象替换数组中的特定对象。我正在使用的方法是在原始数组上使用find,然后覆盖找到的值。据我了解,这将改变原始数组。这种方法似乎成功实现了我的要求,但我在VScode中收到了“变量永不读”的警告。

截图

for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
    let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
        return originalQuestion.originalQ === newQuestionObj.originalQ;
    });

    //change question to new value
    requiredOriginalQuestion = newQuestionObj;
}

这种方法有什么问题,还是应该忽略这个警告?

回答如下:

从数组中获取值时,您将获得对该对象的引用。因此,你的.find的结果是一个变量(称为requiredOriginalQuestion),它“指向”它在数组中找到的对象(allPotentialAnswers)。

当您将newQuestionObj分配给该变量(requiredOriginalQuestion)时,您告诉名为requiredOriginalQuestion的变量停止“指向”您在数组中找到的值,而不是“指向”newQuestionObj。数组中的对象不会以任何方式更改。

要执行您要执行的操作并替换数组中的对象,您需要更改array本身。你可以使用findIndex来做到这一点。

const arr = [{ value: "one" }, { value: "two" }];
const newItem = { value: "Three" };

console.log(arr);

// find the index of the one you want to replace:
const indexToReplace = arr.findIndex(item => item.value === "two");

// Replace the item at that index with the new object
arr[indexToReplace] = newItem;

console.log(arr);

这是JS array.find的错误用法还是要忽略的VSCode警告?

我需要用另一个对象替换数组中的特定对象。我正在使用的方法是在原始数组上使用find,然后覆盖找到的值。据我了解,这将改变原始数组。这种方法似乎成功实现了我的要求,但我在VScode中收到了“变量永不读”的警告。

截图

for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
    let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
        return originalQuestion.originalQ === newQuestionObj.originalQ;
    });

    //change question to new value
    requiredOriginalQuestion = newQuestionObj;
}

这种方法有什么问题,还是应该忽略这个警告?

回答如下:

从数组中获取值时,您将获得对该对象的引用。因此,你的.find的结果是一个变量(称为requiredOriginalQuestion),它“指向”它在数组中找到的对象(allPotentialAnswers)。

当您将newQuestionObj分配给该变量(requiredOriginalQuestion)时,您告诉名为requiredOriginalQuestion的变量停止“指向”您在数组中找到的值,而不是“指向”newQuestionObj。数组中的对象不会以任何方式更改。

要执行您要执行的操作并替换数组中的对象,您需要更改array本身。你可以使用findIndex来做到这一点。

const arr = [{ value: "one" }, { value: "two" }];
const newItem = { value: "Three" };

console.log(arr);

// find the index of the one you want to replace:
const indexToReplace = arr.findIndex(item => item.value === "two");

// Replace the item at that index with the new object
arr[indexToReplace] = newItem;

console.log(arr);
发布评论

评论列表 (0)

  1. 暂无评论