Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแก้ไขเงื่อนไข if ที่ทำงานตลอดเวลาใน JavaScript

คำอธิบาย

ปัญหา: ใช้ = (assignment) แทน == หรือ === (comparison) ในเงื่อนไข if ทำให้เงื่อนไขเป็น true ตลอด

ตัวอย่างโค้ดที่ถูกต้อง

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

ผลลัพธ์

10003 found