หากคุณจะใช้ตัวดำเนินการเท่ากับ (=) ในกรณีที่มีเงื่อนไขว่าบล็อก 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