Definition and Usage
every () method for detecting whether all of the array elements meet the specified criteria (provided by the function).
every () method uses the specified function of all elements in the array detector:
- If the array has a detected element is not satisfied, then the whole expression evaluates to false , and the remaining elements will not be detected.
- If all elements conditions are met, it returns true.
Note: Every () will not be an empty array detection.
Note: Every () does not alter the original array.
grammar
array.every(function(currentValue,index,arr), thisValue)
Parameter Description
parameter | description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | have to. Function, each element of the array will perform this function function parameters:
|
||||||||
thisValue | Optional. Examples of the use of callback object, passed to the function, as the value of "this". If omitted thisValue, "this" value "undefined" |
achieve
// 实现every
Array.prototype.every = function(fn, value){
if (typeof fn !== "function") {
return false;
}
var arr = this;
for (var i = 0; i < arr.length; i++) {
var result = fn.call(value, arr[i], i, arr);
if (!result) return false;
}
return true;
}
test
var arr = [2,23,4,2,4,2,2];
console.log(arr.every(function(item, index, arr){
return item >= 0;
}));