indexOf หาตำแหน่งแรกของค่าที่ระบุในอาร์เรย์ คืนค่า index (เริ่มตั้งแต่ 0) หากพบค่านั้น หรือ -1 หากไม่พบ ฟังก์ชันนี้มีประโยชน์ในการตรวจสอบตำแหน่ง และเข้าถึงข้อมูลใกล้เคียง
=indexOf(array, value, [fromIndex])
=indexOf(array, value, [fromIndex])
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| array | array | Yes | Array ที่ต้องการค้นหา | |
| value | any | Yes | ค่าที่ต้องการค้นหา | |
| fromIndex | number | Optional | 0 | ตำแหน่งเริ่มต้นสำหรับการค้นหา (default คือ 0) |
หาตำแหน่งของสินค้า หรือรายการใดๆ ในอาร์เรย์ เพื่อใช้ในการแก้ไขหรือลบข้อมูล
ใช้ indexOf ร่วมกับเงื่อนไข if เพื่อตรวจสอบว่ามีข้อมูลและได้ตำแหน่งพร้อมกัน
{{ indexOf(['apple', 'banana', 'orange'], 'banana') }}={{ indexOf(['apple', 'banana', 'orange'], 'banana') }}
1
{{ indexOf(['apple', 'banana', 'orange'], 'grape') }}={{ indexOf(['apple', 'banana', 'orange'], 'grape') }}
-1
{{ indexOf($json.products, $json.targetProduct) > -1 ? 'Found' : 'Not Found' }}={{ indexOf($json.products, $json.targetProduct) > -1 ? 'Found' : 'Not Found' }}
Found หรือ Not Found
indexOf() หาเพียง occurrence แรกเท่านั้น หากต้องการหาทั้งหมด ให้ใช้ filter() หรือ map()
หมายความว่าไม่พบค่าที่ระบุในอาร์เรย์ ใช้เงื่อนไข > -1 เพื่อตรวจสอบว่าพบค่าหรือไม่
ใช้เมื่อต้องการหาตำแหน่งของค่าในอาร์เรย์ เพื่อแก้ไข ลบ หรือดำเนินการกับข้อมูลที่พบ
indexOf เป็นฟังก์ชันที่หาตำแหน่ง (index) ของค่าที่ระบุในอาร์เรย์ คืนค่าตำแหน่ง (0-based) ถ้าพบค่า หรือ -1 ถ้าไม่พบ ใช้เพื่อค้นหาตำแหน่งข้อมูล