翻譯不完整。請協助 翻譯此英文文件。
find() 方法,如果一個在陣列中的元素滿足提供的測試函數,則返回一個在陣列中的值。否則回傳 undefined。
也可以參考 findIndex() 方法,它回傳被找到的元素在陣列中的索引,而不是它的值。
語法
arr.find(callback[, thisArg])
參數
callback- 會處理陣列中每個元素的函數,它使用三個參數:
element- 在陣列中正被處理的元素。
index- 在陣列中正被處理的元素的索引。
array- 被處理的陣列。
thisArg- 可選。在回呼函數中會使用的參數。
描述
這個方法會對每個元素執行一次回呼函數,直到找到一個讓回呼函數回傳 true 的元素。當元素被找到的時候,find() 會立刻回傳該元素,否則回傳 undefined。回呼只會調用索引已賦值的陣列,而不會調用已被刪除、或是從未賦值的索引。
回呼函數會使用三個參數:元素的值、索引與正被搜尋的陣列。
如果提供thisArg 給 find(),this 會作為 callback 每次調用的對象。如果沒提供,它會使用 undefined。
find並不會改變呼叫該方法的陣列。
The range of elements processed by find is set before the first invocation of callback. Elements that are appended to the array after the call to find begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are not visited.
範例
在陣列中找質數
以下範例在陣列中找出一個屬於質數的元素,如果裡面不含質數則回傳 undefined。
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
Polyfill
這個方法在 ECMAScript 2015 中首次被規範,可能尚未在所有 JavaScript 應用中被實作。你可以 用以下程式片段來 polyfill Array.prototype.find:
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
規範
瀏覽器支援度
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 45.0 | 25.0 (25.0) | No support | No support | 7.1 |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | No support | No support | 25.0 (25.0) | No support | No support | 8.0 |