我在程序中有以下 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")
时,我应该得到 1
作为返回。
最佳答案
如果你使用[ "ginger", "daisy"].indexOf("daisy")
你得到1作为索引值并且
如果你使用这个[ "ginger", "daisy"].indexOf(answer)
你会得到-1作为索引值..
所以,这可能是由于变量 answer
中可能出现一些空格
你尝试比较两者的长度...
将 answer.length
与 "daisy".length
进行比较,或者尝试此操作,
[ "ginger", "daisy"].indexOf(answer.trim())
。也许您在获取文本长度时会注意到问题..
关于javascript - 在 JS 中测试数组成员资格会产生令人惊讶的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42024581/