const beasts = ['ant', '/bison/', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison')); -> 4 OK
console.log(beasts.indexOf('/bison')) -> -1 NOT FOUND
任何人都知道这种行为的原因是什么?
找不到元素'/bison'
,因为它在您的列表中不存在。您的列表中只有'/bison/
。
console.log(beasts.indexOf('/bison/'))
应该会给您预期的结果。
数组中还有一个斜杠。如果我尝试此代码
console.log(beasts.indexOf('/bison/'));
对我有用,但
console.log(beasts.indexOf('/bison'));
与预期不符,因为它不在数组中。
console.log(beasts.indexOf('/ bison /')); ->这将为您提供1的结果。在-console.log(beasts.indexOf('/ bison'))的情况下,结果为-1,因为它与数组中的任何项目都不匹配。