หา item เฉพาะใน array ใช้ ES6 method Array.find()
ตัวอย่าง array ผัก หา "carot":
const vegetables = ["broccoli", "carot", "kale", "spinach"];
// Find carot in array
let carot = vegetables.find(function(vegetables) {
return vegetables === "carot";
});
console.log(carot); // "carot"
โค้ดทำงานอย่างไร:
- ประกาศตัวแปร
carot - Assign
vegetablesvariable ใส่Array.find()ระบุ return string"carot" - Log ผลลัพธ์
Note 1: Triple equals === เช็ค value equality และ type equality
Note 2: JavaScript case sensitive ถ้า array items ใหญ่ ต้องใช้ uppercase ใน Array.find() ด้วย