Mos*_*rge 0 javascript arrays indexof node.js
我正在学习节点.下面的代码给出了不一致的结果,即,如果我给出argv1.indexOf('test'),那么代码无法找到文本,但是,有时候它返回true.为什么会如此.
function process(argv1) {
if(argv1.indexOf('test')) {
console.log('Text is available in array.');
}
}
process(['test','one','help', 'one', 'two']);
Run Code Online (Sandbox Code Playgroud)
那是因为indexOf返回匹配元素的索引.如果找不到元素,它将返回-1.
你需要的是改变条件:
function process(argv1) {
if(argv1.indexOf('test') !== -1) {
console.log('Text is available in array.');
}
}
process(['test','one','help', 'one', 'two']);
Run Code Online (Sandbox Code Playgroud)
编辑:正如@Havvy指出的那样test,.indexOf将返回0哪个将被转换为false.对于其他数组元素,它们的索引将被转换为true,因为任何非零数字都将被转换为true.有关javascript评估的更多信息,请参阅此处.
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |