PhpStorm 抱怨将键值添加到数组

PhpStorm complains about adding key value to an array

我有以下代码:

            let self = this;
          
            for (const questionIndex in self.questions) {
                self.givenAnswers[questionIndex] = "";
            }

PhpStorm 抱怨 self.givenAnswers[questionIndex] = ""; 行说我需要检查对象是否有 属性。 完整消息是:

Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check.

但是 givenAnswers 变量是一个数组而不是一个对象,我想附加新的键和值。我该如何删除警告,或者代码有什么问题?

虽然您可以添加 hasOwnProperty 检查来修复警告:

for (const questionIndex in self.questions) {
    if (self.questions.hasOwnProperty(questionIndex)) {
        self.givenAnswers[questionIndex] = "";
    }
}

如果它是一个数组,我认为从 0 迭代到它的长度会不那么冗长:

for (let i = 0; i < self.questions.length; i++) {
    self.givenAnswers[i] = "";
}