JS object-array processing method filter method

filter() method

1 , filter () method creates a new array of new elements in the array by checking the specified array qualifying all the elements (if no eligible empty array).

note

The filter() method will not detect the empty array, and will not change the original array;

grammar

array.filter(function(currentValue,index,arr), thisValue)
parameter description
function(currentValue,index,arr)

Must, function, each element in the array will execute the entire function

parameter description
currentValue Required, the value of the current element
index Optional, the index value of the current element
arr Optional, the array object to which the current element belongs
thisValue Optional. The object is used when the callback function is executed. If there is no element that meets the conditions, an empty array is returned.

 

 

 

 

 

 

 

 

 

Practical application (1)


var ages = [32, 33, 16, 40];
let newArr = ages.filter((age) => {
    return age>18
})
console.log(newArr) //[32,33,40]

过滤元素用起来十分方便

Practical application (two)

让数组中指定元素索引的元素排到首位;
let test = [1, 2, 3, 4, 5];
function getSit(index) {
    newarr = (test.filter((x, y) => { return y != index }));
    newarr.unshift(test[index])
    return newarr
}
console.log(getSit(3))

 

Guess you like

Origin blog.csdn.net/qq_40010841/article/details/114142085