我正在学习节点。下面的代码给我不一致的结果,即,如果我给argv1.indexOf('test')
,则代码无法找到文本,但是,有时它返回true。怎么会这样
function process(argv1) {
if(argv1.indexOf('test')) {
console.log('Text is available in array.');
}
}
process(['test','one','help', 'one', 'two']);
最佳答案
这是因为indexOf
返回匹配元素的索引。如果找不到元素,它将返回-1
。
您需要更改条件:
function process(argv1) {
if(argv1.indexOf('test') !== -1) {
console.log('Text is available in array.');
}
}
process(['test','one','help', 'one', 'two']);
编辑:正如@Havvy指出的,在
test
的情况下,.indexOf
将返回0
,该类型将被强制转换为false
。对于其他数组元素,其索引将转换为true
,因为任何非零数字都将转换为true
。有关javascript评估的更多信息,您可以阅读here。关于javascript - 在if语句中对数组使用indexOf的结果不一致,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27369863/