Native JS achieve some () method

Definition and Usage

some () method for detecting elements in the array satisfies the specified conditions (function available).

some () method will execute each element of the array in turn:

  • If there is an element satisfies the condition, the expression returns to true  , the remaining elements will not perform detection.
  • If you do not meet the conditions of the elements, false is returned.

Note:  some () will not be an empty array detection.

Note:  some () does not alter the original array.

grammar

array.some(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:
parameter description
currentValue have to. The current value of the element
index Optional. The current index value of the element
arr Optional. Current array object element belongs
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

// 实现some
Array.prototype.some = 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 true;
    }
    return false;
}

test

var arr3 = [2,23,4,2,4,2,2];
console.log(arr3.some(function(item, index, arr){
    return item >= 6;
}));

Published 167 original articles · won praise 197 · views 290 000 +

Guess you like

Origin blog.csdn.net/qq_17497931/article/details/104644314