在 JS 中测试数组成员会产生令人惊讶的结果
testing for array membership in JS produces surprising results
我在程序中有如下几行JS...
console.log(self.dataset[altAspect][altGroup] + " is the contents of the altGroup");
console.log(answer + " is the answer to be checked");
console.log('it is ' + (self.dataset[altAspect][altGroup].indexOf(answer) > -1) + ' that ' + answer + ' is a member of ' + self.dataset[altAspect][altGroup]);
if (!self.dataset[altAspect][altGroup].indexOf(answer) > -1){
self.wrongGroups.push(altGroup);
console.log('added ' + altGroup + ' to the wrong groups!');
self.altCount++;
}
这会将以下内容记录到控制台:
ginger,daisy is the contents of the altGroup app.js:203:21
daisy is the answer to be checked app.js:204:21
it is false that daisy is a member of ginger,daisy app.js:205:21
added skinny to the wrong groups! app.js:208:25
我的问题是,为什么上面说"daisy"不是["ginger"、"daisy"]的成员?显然,当我 运行 [ "ginger", "daisy" ].indexOf("daisy")
我应该在 return.
中得到 1
如果你使用 [ "ginger", "daisy" ].indexOf("daisy")
你得到 1 作为索引值并且
如果你使用这个 [ "ginger", "daisy" ].indexOf(answer)
你得到 -1 作为索引值..
因此,它可能是由于您的变量中可能出现一些空格而引起的 answer
您尝试比较两者的长度...
比较 answer.length
和 "daisy".length
或者试试这个,
[ "ginger", "daisy" ].indexOf(answer.trim())
。您可能会在获取文本长度时注意到问题..
我在程序中有如下几行JS...
console.log(self.dataset[altAspect][altGroup] + " is the contents of the altGroup");
console.log(answer + " is the answer to be checked");
console.log('it is ' + (self.dataset[altAspect][altGroup].indexOf(answer) > -1) + ' that ' + answer + ' is a member of ' + self.dataset[altAspect][altGroup]);
if (!self.dataset[altAspect][altGroup].indexOf(answer) > -1){
self.wrongGroups.push(altGroup);
console.log('added ' + altGroup + ' to the wrong groups!');
self.altCount++;
}
这会将以下内容记录到控制台:
ginger,daisy is the contents of the altGroup app.js:203:21
daisy is the answer to be checked app.js:204:21
it is false that daisy is a member of ginger,daisy app.js:205:21
added skinny to the wrong groups! app.js:208:25
我的问题是,为什么上面说"daisy"不是["ginger"、"daisy"]的成员?显然,当我 运行 [ "ginger", "daisy" ].indexOf("daisy")
我应该在 return.
1
如果你使用 [ "ginger", "daisy" ].indexOf("daisy")
你得到 1 作为索引值并且
如果你使用这个 [ "ginger", "daisy" ].indexOf(answer)
你得到 -1 作为索引值..
因此,它可能是由于您的变量中可能出现一些空格而引起的 answer
您尝试比较两者的长度...
比较 answer.length
和 "daisy".length
或者试试这个,
[ "ginger", "daisy" ].indexOf(answer.trim())
。您可能会在获取文本长度时注意到问题..