javascript - 在 if 语句中对数组使用 indexOf 的结果不一致

标签 javascript arrays node.js indexof

我正在学习 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/

相关文章:

javascript - Chart.js 使用 X 轴时间动态更新图表

javascript - 使用键将数组的数组转换为对象

c - 为什么我不能在 C 中传递的函数内打印数组的大小?

node.js - heroku 应用程序因 socket.io 崩溃

node.js - npm 错误! azure devops 中的代码 ELIFECYCLE 无法使其运行

javascript - 如何阻止 Safari 在我的 <input type ="search"> 字段中放置放大镜图像?

javascript - 选择元素文本并添加逗号

javascript - NodeTime中ISO-8601格式值的偏移格式从何而来?

javascript - 如何连接数组值作为键来获取 json 对象值

javascript - 如何使用按钮和jquery向 Node 发送DELETE请求?