มีวิธีต่างๆ เช็ค existence ของ object/key ใน array และ object มาดู object ก่อน
เช็ค key ใน object ใช้ in operator
ตัวอย่าง
let obj = { name: "John", age: 22 } console.log('name' in obj); console.log('address' in obj);ผลลัพธ์
true false
หมายเหตุ - in operator คืน true ถ้า property อยู่ใน object หรือ prototype chain
เช็ค object ใน array ใช้ indexOf method บน array ไม่เจอคืน -1 เจอคืน index
ตัวอย่าง
let arr = ["test", 1, 2, "hello", 23.5]; console.log(arr.indexOf({})) console.log(arr.indexOf("hello")) console.log(arr.indexOf(23.5))ผลลัพธ์
-1 3 4