我在程序中有以下几行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作为回报。

最佳答案

如果使用[ "ginger", "daisy" ].indexOf("daisy"),则索引值为1,并且

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

因此,它可能是由于变量answer中可能出现空格引起的

您尝试比较两者的长度...

answer.length"daisy".length比较,否则尝试一下,

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

10-04 14:09