我正在尝试制作一个ID搜索器,当您输入正确的ID时它会做某事。但是,JavaScript if语句始终运行。怎么样?
如果在if条件中使用相等的运算符(=),则将始终执行if块。
您需要使用==运算符或===。
示例
以下是代码-
var details = [
{
id: 10001,
name: "John"
},
{
id: 10002,
name: "Bob"
},
{
id: 10003,
name: "Carol"
},
{
id: 10004,
name: "David"
}
]
var searchId = 10003;
for (var index = 0; index < details.length; index++) {
if (details[index].id === searchId) {
console.log(details[index].id + " found");
break;
}
}要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo322.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\javascript-code> node demo322.js 10003 found