我正在学习 Node 。以下代码给出了不一致的结果,即如果我给出 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/