The use of for, while, do While, for in, forEach, map, reduce, every, some, filter

The use of for, while, do While, for in, forEach, map, reduce, every, some, filter

for

let arr = [2, 4, 6, 56, 7, 88];

//for
for (let i = 0; i < arr.length; i + + ) {<!-- -->
console.log(i + ':' + arr[i]) //0:2 1:4 2:6 3:56 4:7 5:88
}

An ordinary for loop can use the index of the array to access or modify the corresponding elements of the original array, that is, the data of the original array can be modified.

while

//while
let arr=[1,0,8,7],i=0;
while(i<arr.length){<!-- -->
    console.log(i + ':' + arr[i]);//0:1 1:0 2:8 3:7
    i + + ;
}

do while

//do while
let arr=[1,0,8,7],i=0;
do{<!-- -->
    console.log(i + ':' + arr[i]);//0:1 1:0 2:8 3:7
    i++
}while(i<arr.length)

for in

let obj = {<!-- -->
name: 'Xiao Ming',
age: 18,
hobby: 'run,song,game'
};

for(let key in obj){<!-- -->
    console.log(key + ':' + obj[key]) //name:Xiao Ming age:18 hobby:run,song,game
}

Note that objects can also be traversed.

for of

let arr = [2, 4, 6, 56, 7, 88];
let obj = {<!-- -->
name: 'Xiao Ming',
age: 18,
hobby: 'run,song,game'
};
for(let value of arr){<!-- -->
    console.log(value) //2 4 6 56 7 88
}

for (let [key, value] of arr.entries()) {<!-- -->
    console.log(key + ':' + value); //0:2 1:4 2:6 3:56 4:7 5:88
}

for (let [key, value] of Object.entries(obj)) {<!-- -->
    console.log(key + ':' + value); //name:Xiao Ming age:18 hobby:run,song,game
}

Note: This for of can traverse both lists and objects.

forEach

The most memory-saving traversal method, but you cannot use break or return

let arr = [2, 4, 6, 56, 7, 88];
let obj = {<!-- -->
name: 'Xiao Ming',
age: 18,
hobby: 'run,song,game'
};
arr.forEach((value,key)=>{<!-- -->
console.log(key + ':' + value) //0:2 1:4 2:6 3:56 4:7 5:88
})

Object.keys(obj).forEach((value)=>{<!-- -->
console.log(value) //"name", "age", "hobby"
})

You can iterate over both lists and objects.

Note: forEach will change the value in the original array.

let arr = [
{<!-- --> id: '01001', title: 'Postgraduate Entrance Examination Results' },
{<!-- --> id: '01002', title: 'China's economic recovery progress bar' },
]
arr.forEach(function(item,index,arr){<!-- -->
item.date = "2023-1-1"
})

console.log(arr)

We have changed the original array, and, as can be seen from the above example, in js, you can directly add an attribute that does not exist to an object.

map

The same way as forEach is written, each loop is equivalent to creating a new data in the memory, which takes up more memory. The difference from forEach is that it can return. Return an array.

let arr = [2, 4, 6, 56, 7, 88];
let obj = {<!-- -->
name: 'Xiao Ming',
age: 18,
hobby: 'run,song,game'
};
arr.map((value,index)=>{<!-- -->
    console.log(index + ':' + value) //0:2 1:4 2:6 3:56 4:7 5:88
})

Object.values(obj).map((value,key)=>{<!-- -->
    console.log(key + ':' + value) //0:Xiao Ming 1:18 2:run,song,game
})

console.log(Object.keys(obj)) // (3) ["name", "age", "hobby"]
console.log(Object.values(obj)) // (3) ["Xiao Ming", 18, "run,song,game"]

Note: The map method will not change the original array

let arr = [1,2,3,4,5]
let newArr = arr.map(function(item,index,arr){<!-- -->
return item*2
})
console.log(arr) // [1,2,3,4,5]
console.log(newArr) // [2,4,6,8,10]

However, modification of attributes in the reference type in the array will still affect the attribute values of the objects in the original array. The effect is the same as forEach.

let arr = [
{<!-- --> id: '01001', title: 'Postgraduate Entrance Examination Results' },
{<!-- --> id: '01002', title: 'China's economic recovery progress bar' },
]

let newArr = arr.map(function(item,index,arr){<!-- -->
item.date = "2023-1-1"
    return item
})
console.log("arr",arr)
console.log("newArr",newArr)

But we can use {…item} to make a copy, and then we can modify the copied value, so that it will not affect the original array data.

let arr = [
{<!-- --> id: '01001', title: 'Postgraduate Entrance Examination Results' },
{<!-- --> id: '01002', title: 'China's economic recovery progress bar' },
]

let newArr = arr.map(function(item,index,arr){<!-- -->
item = {<!-- -->...item} // Here we have one more step of copy processing
item.date = "2023-1-1"
return item
})

console.log("arr",arr)
console.log("newArr",newArr)

Extensions:

Usage of… in js

1.What is…

…is the spread operator, which is the new syntax of es6

2. How to use

Acts on an object, returns an object, takes out all traversable properties of the object, and returns a new object that can be copied.

  1. Basic usage

    let person = {<!-- --> name:'Zhang San', age:18}
     
    let someone = {<!-- -->...person}
     
    console.log(someone) //Return { name:'Zhang San', age:18 }
    
  2. Acts on array objects

    et array = ['a','b','c']
    
    let obj = {<!-- -->...array}
     
    console.log(obj) // {0:'a',1:'b',2:'c'} Description: Generate a key for each element of the array and return a new object starting from 0
    
  3. Merge objects

    let name = {<!-- --> name:'Zhang San' }
     
    let age = {<!-- --> age:18 }
     
    let person = {<!-- --> ...name,...age }
     
    console.log(person) //{name:'Zhang San',age:18}
    
  4. Merging of attributes

    let person = {<!-- -->name: "Amy", age: 15};
     
    let someone = {<!-- --> ...person, name: "Mike", age: 17};
     
    console.log(someone); //{name: "Mike", age: 17} Note: When the custom attributes and extended attributes are the same, they will be overwritten. If the custom attribute comes first, the extended attribute overrides the custom attribute. On the contrary, the custom attribute overrides the extended attribute.
    

filter

Function: Does not affect the original array, this method will return a new array. If the callback function returns true, the filter will add this item to the new array to be returned as an element.

Note: return is required in the function passed in, because the data will be filtered based on whether the return value is false or true.

Several situations of filter are as follows:

(1) Directly return a Boolean value. If it is true, the element value is put into the array, and if it is false, it is filtered out.

Example 1:

let arr = [
{<!-- --> id: '01001', title: 'Postgraduate Entrance Examination Results', isHot: true },
{<!-- --> id: '01002', title: 'China's economic recovery progress bar', isHot: false },
]

let result = arr.filter((item) => {<!-- -->
return item.isHot
})

console.log(result) // [{ id: '01001', title: 'Postgraduate Entrance Examination Results', isHot: true }]

// Looking at the print results, you can see that the object data whose isHot is false has been filtered out.

Example 2:

let arr = [1,2,3,4,5];
let result = arr.filter(function(item, index) {<!-- -->
    return item>2;
});
console.log(result);
//output[3, 4, 5]
// item: current element index: index value of current element

(2) When returning a non-Boolean value, the array will also be filtered by implicitly converting the data into a Boolean value.

example:

let arr = [1,undefined,null,3,0,"",NaN]
let result = arr.filter((item) => {<!-- -->
return item
})

console.log(result) // [1, 3]

// After converting the item value into a Boolean value, elements that are false are filtered out, leaving only elements that are true.

(3) Used in combination with other methods:

Here is a small example to help you recall the usage of the indexOf() method of an array: it is used to return the index value where a specified value first appears in the array. If no matching element is found, -1 is returned.

let arr = [1, 2, 3, 4, 5];
let index = arr.indexOf(2);
// Find whether there is an element 2 in the array
console.log(index) //The print result is 1, indicating that 2 matches the value of the element with index 1 in the array

① Use in combination with the indexOf() method to deduplicate arrays:

let arr = [1,1,2,4,5,6,5,5,6]
let newArr = arr.filter((item,index)=>{<!-- -->
return arr.indexOf(item) === index
// Because indexOf always returns the index of the first element that meets the condition
// Repeated values in the array cannot satisfy the congruence judgment and will be filtered out.
})

console.log(newArr) // [1,2,4,5,6]

②Also used with the map method:

let arr = [
{<!-- --> id: '01001', title: 'Postgraduate Entrance Examination Results', isHot: true },
{<!-- --> id: '01002', title: 'China's economic recovery progress bar', isHot: false },
]

// Use the map method to add date attributes to the data

let result = arr.map((item) => {<!-- -->
item = {<!-- -->...item}
item.date = '2023-01-01'
return item
    //After the map method, use the filter method to filter the data.
}).filter((item) => {<!-- -->
return item.isHot === true
})

console.log(result)

reduce

Function: Traverse the array and construct a final value.

Syntax: array.reduce(function(previous,current,index,arr),initValue);

Parameter Description:

① When the second parameter initValue is not passed, we use an example of calculating the sum of array elements:

let arr = [1,3,5,7]
let result = arr.reduce((previous,current)=>{<!-- -->
console.log('previous:',previous, ' current:',current)
return previous + current
})

console.log('result:',result)

The printed result is:

We can see that:

  • The incoming arrow function executes the array length – 1 times, which is 3 times;

  • The callback function is called multiple times:

    When called for the first time, previous represents the value 1 of the first element of the array, and current represents the value 3 of the second element of the array;

    When called for the second time, previous represents the value returned in the last call, which is 1 + 3 as 4, and current is the value of the third element of the array, 5;

    When called for the third time, previous also represents the value returned by the last call, which is 4 + 5, which is 9, and current represents the value of the fourth element of the array, 7.

  • The value of result is the result value 16 of the last calculation of 9 + 7.

② When passing in the second parameter initValue, we use an example to illustrate that each element of the new array is the cumulative sum of each element of the original array:

let arr = [1,3,5,7]
let sum = 0
let result = arr.reduce((previous,current)=>{<!-- -->
console.log(previous, 'current:', current)
previous.push(sum + current)
sum + = current
return previous
}, [])

console.log('result:', result)

The printed result is:

We can see that:

  • The incoming arrow function is executed the same number of times as the length of the arr array, which is 4 times;
  • previous: When the arrow function is called for the first time, it represents the initial value initValue passed in, which is an empty array, and the following represents the value returned last time; current: always represents the value of each element of the array arr. ;
  • result also represents the result returned by the last arrow function call return.

Examples of use of reduce:

Above we gave two simple examples to distinguish the difference between one parameter and two parameters passed in to the reduce method. Next, I will use an example of calculating the number of products selected in a shopping cart to illustrate the specific application scenarios of reduce in the project.

There are currently 3 products in the shopping cart, 2 of which are selected, and the total selected price is calculated to be 22393. We can calculate the two values ①② through the reduce method.

// arr represents an array of all products in the shopping cart, and the unused data is omitted.
let arr = [
    {<!-- -->
        id:12334,isChecked:1, // 1 means this product is selected in the shopping cart
        cartPrice:5999, // indicates the unit price of the product is 5999
        skuNum:1, // Indicates that the number of products in the shopping cart is 1
        skuName: "Xiaomi 10 Extreme Commemorative Edition Dual-mode 5G Snapdragon 865 120W Fast Charging 8GB + 128GB Ceramic Black Gaming Phone",
    },{<!-- -->
        id:12375,
        isChecked:0, // 0 means the product is not selected in the shopping cart
        cartPrice:2323, // Indicates that the unit price of the product is 2323
        skuNum:1, // Indicates that the number of products in the shopping cart is 1
        skuName: "Huawei P40 5G full network smartphone supports HarmonyOS Zero White 8G + 128G",
    },{<!-- -->
        id:12376,
        isChecked:1, // 1 means this product is selected in the shopping cart
        cartPrice:8197, // Indicates that the unit price of the product is 8197
        skuNum:1, // Indicates that the number of products in the shopping cart is 1
        skuName: "Apple iPhone 12 (A2404) 64GB Black Supports China Mobile, China Unicom and Telecom 5G Dual SIM Dual Standby Mobile Phone",
    }
]

Because the isChecked attribute of each product object means 1 is selected and 0 means not selected, we can calculate the number of products selected in the shopping cart by cumulatively adding this value:

// Calculate the number of products selected in the shopping cart
let num = arr.reduce((previous,current)=>{<!-- -->
return previous + current.isChecked
// The initial value of previous is the second parameter 0 passed in, and current represents the object currently traversed in the array.
},0)

// By accumulating and adding the isChecked attribute values of all products, the number of selected products num is 2.

//Calculate the total price of the selected products. We also calculate cumulatively through the reduce method:

// Calculate the total price of the products selected in the shopping cart
let price = arr.reduce((previous,current)=>{<!-- -->
    return previous + current.isChecked * current.cartPrice * current.skuNum
    // The product quantity and price of the selected product are added together.
},0)

//The final price value is the total price of the selected product

From the above example, we can see that in this situation where data needs to be accumulated and processed, using the reduce method is a more convenient operation.

some and every

Because the some() method and every() method are relatively simple and similar, they will be explained together here.

(1) The some() method is used to detect whether the elements in the array satisfy the return judgment condition. If one element satisfies the condition, the expression returns true, and the remaining elements will not be tested again; if there is no element that satisfies the condition, Returns false.

//Some methods will return true as long as one element meets the return condition, and subsequent elements will not be judged again.
let arr = [2,3,4,6]
let result = arr.some((item)=>{<!-- -->
return item % 2 === 1 // Determine whether each element of the array can be divided by 2 to leave a remainder of 1
})
console.log(result) // Because the second element 3 matches, the result is true

(2) The every() method is used to detect whether all the elements in the array meet the return judgment condition. As long as one of the elements does not meet the requirement, it will return false. If all elements meet, it will return true.

//The every method requires that all elements meet the return judgment conditions before returning true, otherwise it returns false
let arr = [2,3,4,6]
let result = arr.every((item)=>{<!-- -->
return item % 2 === 0 // Determine whether each element of the array is divisible by 2
})
console.log(result) // Because the second element 3 does not meet the condition, the result is false

Summary:

for: simple, you can access or modify the original array through index

while, do while: The loop condition is determined, the same as java

for in: You can traverse the properties and property values of the object.

for of: can traverse both lists and objects. You can get the index and value of the list, or you can get the attributes and attribute values of the object.

forEach: saves memory, but you cannot use break in for search. You can get the index and elements of the array. You can get the property values in the object. Note: forEach will change the value in the original array. The forEach method has no return value and is generally used to directly modify the original array;

map: The original array will not be changed. However, reference data types will still affect the properties of the objects in the original array. But you can use the {… object} syntax to solve this problem. map will return an array object, which is the changed object.

filter: The filter() method is used to filter the list, and the returned result is the new filtered array. This is still very useful.

reduce: Generally we use it for accumulation

some: Determine whether an element in the list meets a certain rule

every: Determines whether all elements in the list comply with a certain rule

Note: In js, you can directly add attributes that are not originally available to an object.