Common methods of js array traversal (ES5)+(ES6)

for loop (ES5)

The simplest loop traversal method is also the most frequently used one, which can be optimized

For a for loop, the loop condition is always executed once more than the loop body

const arr = [1, 2, 3]

 for(let i = 0; i < arr.length; i++) {
     console.log(arr[i])  // 1 2 3
 }

for…in (ES5)

The for...in loop is not recommended to be used on arrays . for...in is built for traversing object properties. Of course, arrays can also be used

for...in循环Be careful during use, problems may occur

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for(let index in arr) {
    console.log(index);
}
 // 0 1 2 3 4 5 6 7 8

forEach() (ES5)

语法:array.forEach(callbackFn(currentValue, index, arr), thisValue)

Other syntax:

// arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// inline callback function
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* ... */ })
forEach(function(element, index, array){ /* ... */ })
forEach(function(element, index, array) { /* ... */ }, thisArg)

The forEach loop has no return value . How many elements are there in the array? The callback in this method will be executed several times.

The forEach loop itself does not support continue and break statements

continue can be replaced by return false or return true

break can be replaced by try catch/every/some

const arr = [1, 2, 3, 4, 5, 6];

arr.forEach((item, index, arr) => {
    console.log(item)  // 当前元素 1 2 3 4 5 6 
    console.log(index)  // 数组里当前元素的索引值 0 1 2 3 4 5 
});

map() (ES5)

The map() method returns a new array , and the elements in the array are the values ​​processed by calling the function on the original array elements

The map loop must return

The map loop does not change the original array

语法:array.map(function(currentValue, index, arr), thisValue) 

 let arr = [1, 2, 3, 4, 5]

 let newArr = arr.map(item => {
    return item + 1
 })
 console.log(arr,newArr) 
 // 1 2 3 4 5 
 // 2 3 4 5 6

filter() (ES5)

The filter() loop returns a new array that meets the conditions , and the elements in the new array are checked by checking all elements in the specified array that meet the conditions

The filter loop does not change the original array

 语法:array.filter(function(currentValue,index,arr), thisValue)

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const res = arr.filter((item,index,arr)=>{
    return item > 3;
});
console.log(arr,res) 
// 1, 2, 3, 4, 5, 6, 7, 8, 9
// 4, 5, 6, 7, 8, 9

some() (ES5)

some Loop to find any eligible element in the array and return a boolean value , traverse the array, return true as long as more than one element meets the condition , otherwise return false, and exit the loop

some loop does not change the original array

const arr = [1, 2, 3, 4, 5];

const res = arr.some((item,index,arr) =>{
    return item > 3
})
console.log(res)  // true 

every() (ES5)

every Loop to find all eligible elements in the array and return a boolean value , return true only when all elements in the array meet the conditions , otherwise return fasle 

every loop does not change the original array

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const res = arr.every((item,index,arr)=>{
    return item > 3
})
console.log(res);  // false

reduce() (ES5)

The reduce loop takes in a function as an accumulator, and each value in the array (from left to right) is initially reduced to a final value.

 语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

 Simple usage of reduce 

const arr = [1, 2, 3, 4];
const mul = arr.reduce((x,y)=>x*y)
console.log( mul );  // 求乘积 24

const arr = [1,2,3,4]
const sum = arr.reduce((pre,cur)=>{
    return pre +cur
})
console.log(sum)  // 求和 10

 Advanced usage of reduce

 Count the number of occurrences of each element in an array

let person = ['张三','李四','王五','张三','赵六','王五']
let nameObj = person.reduce((pre,cur) =>{
    if( cur in pre){
        pre[cur]++
    }
    else{
        pre[cur] = 1
    }
    return pre
}, {})
console.log(nameObj) // {张三: 2, 李四: 1, 王五: 2, 赵六: 1}

Array deduplication

indexOf() returns the position of the first occurrence of a specified string value in the string

Returns -1 if no matching string is found

let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);// [1, 2, 3, 4]


let arr = [1,2,3,4,4,1]
let res = arr.reduce((pre,cur){
     pre.indexOf(cur) == -1 && pre.push(cur)
     return pre
},[])
console.log(pre);// [1, 2, 3, 4]

Convert two-dimensional array to one-dimensional

concat() is used to concatenate two or more arrays.

concat() does not change the existing array, but returns a new array containing the values ​​of the concatenated arrays

let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]

Convert multidimensional array to one-dimensional

let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
   return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]

find() (ES6)

find() traverses the array and returns the first element that meets the criteria , or undefined if there is no element that meets the criteria

let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
let num = arr.find(function (item, index) {
	return item === 3
})
console.log(num)  // 3
  let arr = [1,2,2,3,3,3,3,4,4,5,6]
  let num = arr.find((item:any) => {
      return item === 10
  })
  console.log(num)  // undefined

findIndex() (ES6)

findIndex() traverses the array and returns the index of the first element that meets the condition , or -1 if there is no element that meets the condition

let arr = [1, 3, 7, 2, 3, 3, 4, 5, 6]   
let num = arr.findIndex(function (item) {
	return item === 7
})
console.log(num)   //  2
 let arr = [1,2,2,3,3,3,3,4,4,5,6]
 let num = arr.findIndex((item:any) => {
     return item === 10
 })
console.log(num)  // -1

for…of…(ES6)

Objects cannot be looped, because any data structure can complete the traversal operation as long as it deploys the Iterator interface. Some data structures have native Iterator interfaces, such as Array, Map, Set, String, etc., and the Iterator interface is deployed on the Symbol.iterator property of the data structure On the above, and the object Object just does not have the Symbol.iterator property, so it cannot be traversed by for..of

for...of...  returns the corresponding content

const arr = ['我', '是', '谁', '我', '在', '哪'];

for(let item of arr) {
    console.log(item);
}
// 我 是 谁 我 在 哪

values()

The values ​​method  returns the corresponding content

const arr = ['我', '是', '谁', '我', '在', '哪'];

for(let item of arr.values()) {
    console.log(item);
}
// 我 是 谁 我 在 哪

entries()

The entries method returns the corresponding value and subscript value

const arr = ['我', '是', '谁', '我', '在', '哪'];

for(let [index,item] of arr.entries()) {
    console.log(index,item);
}
// 0 我
// 1 是 
// 2 谁 
// 3 我 
// 4 在 
// 5 哪

Guess you like

Origin blog.csdn.net/m0_56471534/article/details/129817994