--- title: Array.prototype.indexOf() slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf ---
Phương thức indexOf() sẽ trả về giá trị index đầu tiên của mảng, nơi mà nó đc tìm thấy trong mảng, hoặc trả về -1 nếu không tồn tại trong mảng.
Chú ý: sử dụng indexOf() cho String, xem ở đây {{jsxref("String.prototype.indexOf()")}}.
arr.indexOf(searchElement[, fromIndex])
searchElement
fromIndex
{{optional_inline}}fromIndex
là một số âm, vị trí index được tính từ cuối mảng. Lưu ý: cho dù fromIndex
là số âm, kết quả tìm kiếm vẫn tính từ đầu mảng trở về sau. Nếu index bằng 0, cả mảng sẽ được tìm kiếm. Mặc định: 0 (cả mảng sẽ được tìm kiếm)Index đầu tiên của phần tử tìm thấy trong mảng; -1 nếu không tìm thấy.
indexOf()
sẽ so sánh giá trị searchElement
với các phần tử của mảng sử dụng so sánh chặt (tương đương với việc so sánh toán tử ba-dấu-bằng ===
)
indexOf()
Ví dụ sau sẽ dùng indexOf()
để tìm vị trí của giá trị trong một mảng.
var array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.indexOf(element); while (idx != -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4]
function updateVegetablesCollection (veggies, veggie) { if (veggies.indexOf(veggie) === -1) { veggies.push(veggie); console.log('New veggies collection is : ' + veggies); } else if (veggies.indexOf(veggie) > -1) { console.log(veggie + ' already exists in the veggies collection.'); } } var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; updateVegetablesCollection(veggies, 'spinach'); // New veggies collection is : potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, 'spinach'); // spinach already exists in the veggies collection.
indexOf()
được thêm vào đặc tả ECMA-262, phiên bản 5; nên có thể nó không có sẵn trong tất cả trình duyệt. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script. Polyfill này sẽ giúp bạn vẫn sử dụng được indexOf
dù trình duyệt nào đó vẫn chưa hỗ trợ sẵn. Giải thuật của polyfill này tương đương với đặc tả của indexOf
trong ECMA-262, 5th edition, với yêu cầu {{jsxref("Global_Objects/TypeError", "TypeError")}} và {{jsxref("Math.abs()")}} không bị thay đổi.
// This version tries to optimize by only checking for "in" when looking for undefined and
// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.
// Whether it is actually faster remains to be seen.
if (!Array.prototype.indexOf)
Array.prototype.indexOf = (function(Object, max, min) {
"use strict"
return function indexOf(member, fromIndex) {
if (this === null || this === undefined)
throw TypeError("Array.prototype.indexOf called on null or undefined")
var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len)
if (i < 0) i = max(0, Len + i)
else if (i >= Len) return -1
if (member === void 0) { // undefined
for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i
} else if (member !== member) { // NaN
return -1 // Since NaN !== NaN, it will never be found. Fast-path it.
} else // all else
for (; i !== Len; ++i) if (that[i] === member) return i
return -1 // if the value was not found, then return -1
}
})(Object, Math.max, Math.min)
Tuy nhiên, nếu bạn muốn hiểu rõ mọi chi tiết của đặc tả ECMA, và không mấy quan tâm đến performance hay cần phải ngắn gọn, thì bạn nên tham khảo đoạn polyfill bên dưới:
// Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let o be the result of calling ToObject passing // the this value as the argument. if (this == null) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of o with the argument "length". // 3. Let len be ToUint32(lenValue). var len = o.length >>> 0; // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = fromIndex | 0; // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of o with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of o with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in o && o[k] === searchElement) { return k; } k++; } return -1; }; }
Đặc tả | Trạng thái | Ghi chú |
---|---|---|
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}} | {{Spec2('ES5.1')}} | Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.6. |
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Array.indexOf")}}
-0
. Ví dụ: [0].indexOf(0, -0)
sẽ luôn trả về +0
({{bug(1242043)}}).