在JS中测试数组成员资格会产生令人惊讶的结果

时间:2017-02-03 12:41:37

标签: javascript arrays membership

我在程序中有以下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

我的问题是,为什么上面说“雏菊”不是[“姜”,“雏菊”]的成员?显然,当我运行[ "ginger", "daisy" ].indexOf("daisy")时,我应该得到1作为回报。

1 个答案:

答案 0 :(得分:1)

如果你使用[ "ginger", "daisy" ].indexOf("daisy"),你得到1作为索引值和

如果您使用此[ "ginger", "daisy" ].indexOf(answer),则获得-1作为索引值..

因此,可能是由于变量answer

中可能出现一些空格而引起的

你试着比较两者的长度......

answer.length"daisy".length进行比较,否则请尝试此操作,

[ "ginger", "daisy" ].indexOf(answer.trim())。在获取文本长度时,你可能会发现问题。