gpt4 book ai didi

javascript - 这是 JS array.find 的错误使用还是需要忽略的 VSCode 警告?

转载 作者:太空宇宙 更新时间:2023-11-04 03:01:35 25 4
gpt4 key购买 nike

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

屏幕截图

error displayed

代码

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

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

这种方法有什么问题吗?或者我应该忽略这个警告吗?

最佳答案

这里的问题是你的范围。让我们一步一步来:

for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
// defining the variable
let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
return originalQuestion.originalQ === newQuestionObj.originalQ;
});
//useless find.... because you are going to kill the result of the find.

// reassign the variable to a new thing
requiredOriginalQuestion = newQuestionObj;
} // < -- here, requiredOriginalQuestion DIES.

所以基本上,以更简单的方式发生的事情是这样的

for (let something from someArray){
let newvar = doExpensiveCalculation();
newvar = "--";
// and we didnt do anything with it, despite of reassigning to "--"
} <-- newvar doesnt exist anymore.

或更明确地说:

for (let something from someArray){
// lets keep doing nothing :D
}

所以基本上你的警告是这样的

requiredOriginalQuestion is declared but its value is never read.

发生这种情况是因为在每个循环结束时,您没有对 let requiredOriginalQuestion 执行任何操作。您也可以检查它是否会消失,执行以下操作:

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

const stringified = JSON.stringify(requiredOriginalQuestion);
}

但是你会得到类似的东西:

stringified is declared but its value is never read.

终于

如果您想使用查找结果的响应覆盖该值,这就是您所需要的:

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

这样你就不会收到任何警告;)

关于javascript - 这是 JS array.find 的错误使用还是需要忽略的 VSCode 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54669367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com