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

การคืนค่าที่ถูกต้องจาก recursive indexOf ใน JavaScript

คำอธิบาย

เขียนฟังก์ชัน indexOf แบบ recursive คืนค่าดัชนีถ้าพบ ไม่อย่างนั้นคืน -1

ตัวอย่างโค้ด

const indexOf = (arrayValues, v, index = 0) =>
  index >= arrayValues.length
    ? -1
    : arrayValues[index] === v
      ? index
      : indexOf(arrayValues, v, index + 1);

console.log(indexOf(["John", "David", "Bob"], "Adam")); // -1
console.log(indexOf(["Mike", "Adam", "Carol", "Sam"], "Sam")); // 3

วิธีรัน

node fileName.js

ผลลัพธ์

-1
3