indexOf带有内容斜杠的数组的奇怪行为

问题描述 投票:-1回答:3
const beasts = ['ant', '/bison/', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison')); -> 4 OK

console.log(beasts.indexOf('/bison')) -> -1 NOT FOUND

任何人都知道这种行为的原因是什么?

javascript arrays indexof
3个回答
0
投票

找不到元素'/bison',因为它在您的列表中不存在。您的列表中只有'/bison/

console.log(beasts.indexOf('/bison/'))应该会给您预期的结果。


0
投票

数组中还有一个斜杠。如果我尝试此代码

console.log(beasts.indexOf('/bison/'));

对我有用,但

console.log(beasts.indexOf('/bison'));

与预期不符,因为它不在数组中。


0
投票

console.log(beasts.indexOf('/ bison /')); ->这将为您提供1的结果。在-console.log(beasts.indexOf('/ bison'))的情况下,结果为-1,因为它与数组中的任何项目都不匹配。

© www.soinside.com 2019 - 2024. All rights reserved.