JavaScript Array indexOf ()

Phương thức JavaScript Array indexOf () trả về chỉ số đầu tiên về sự xuất hiện của một phần tử mảng hoặc -1 nếu nó không được tìm thấy.

Cú pháp của indexOf()phương thức là:

 arr.indexOf(searchElement, fromIndex)

Ở đây, arr là một mảng.

tham số indexOf ()

Các indexOf()phương pháp có trong:

  • searchElement - Phần tử cần định vị trong mảng.
  • fromIndex (tùy chọn) - Chỉ mục để bắt đầu tìm kiếm tại. Theo mặc định, nó là 0 .

Giá trị trả về từ indexOf ()

  • Trả về chỉ số đầu tiên của phần tử trong mảng nếu nó có mặt ít nhất một lần.
  • Trả về -1 nếu phần tử không được tìm thấy trong mảng.

Lưu ý: indexOf() so sánh searchElementvới các phần tử của Mảng bằng cách sử dụng bình đẳng nghiêm ngặt (tương tự như toán tử ba-bằng hoặc ===).

Ví dụ 1: Sử dụng phương thức indexOf ()

 var priceList = (10, 8, 2, 31, 10, 1, 65); // indexOf() returns the first occurance var index1 = priceList.indexOf(31); console.log(index1); // 3 var index2 = priceList.indexOf(10); console.log(index2); // 0 // second argument specifies the search's start index var index3 = priceList.indexOf(10, 1); console.log(index3); // 4 // indexOf returns -1 if not found var index4 = priceList.indexOf(69.5); console.log(index4); // -1

Đầu ra

 3 0 4 -1

Ghi chú:

  • Nếu fromIndex> = array.length , mảng không được tìm kiếm và -1 được trả về.
  • Nếu fromIndex <0 , chỉ số được tính ngược lại. Ví dụ, -1 biểu thị chỉ số của phần tử cuối cùng, v.v.

Ví dụ 2: Tìm tất cả các lần xuất hiện của một phần tử

 function findAllIndex(array, element) ( indices = (); var currentIndex = array.indexOf(element); while (currentIndex != -1) ( indices.push(currentIndex); currentIndex = array.indexOf(element, currentIndex + 1); ) return indices; ) var priceList = (10, 8, 2, 31, 10, 1, 65, 10); var occurance1 = findAllIndex(priceList, 10); console.log(occurance1); // ( 0, 4, 7 ) var occurance2 = findAllIndex(priceList, 8); console.log(occurance2); // ( 1 ) var occurance3 = findAllIndex(priceList, 9); console.log(occurance3); // ()

Đầu ra

 (0, 4, 7) (1) ()

Ví dụ 3: Tìm nếu phần tử tồn tại khác Thêm phần tử

 function checkOrAdd(array, element) ( if (array.indexOf(element) === -1) ( array.push(element); console.log("Element not Found! Updated the array."); ) else ( console.log(element + " is already in the array."); ) ) var parts = ("Monitor", "Keyboard", "Mouse", "Speaker"); checkOrAdd(parts, "CPU"); // Element not Found! Updated the array. console.log(parts); // ( 'Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU' ) checkOrAdd(parts, "Mouse"); // Mouse is already in the array.

Đầu ra

Không tìm thấy phần tử! Đã cập nhật mảng. ('Màn hình', 'Bàn phím', 'Chuột', 'Loa', 'CPU') Chuột đã có trong mảng.

Đề xuất đọc: JavaScript Array.lastIndexOf ()

thú vị bài viết...