Reprint links: blog.csdn.net/u010047432/… www.jiangweishan.com/article/js8…

Functions that iterate over a number group in JS include: for, for… in… ForEach, some, map, filter, every ES6 ForEach (), map(), include(), indexOf(), filter(), some(), every () can be used for object (array) merge, de-duplicate Set objects

1. For and for in for loops are the basic syntax used to write JS:

for(statement1; statements2; statements3) {block of code executed}Copy the code

Statement 1 executes before the loop (block of code) begins statement 2 defines the condition statement 3 that runs the loop (block of code) to execute after the loop (block of code) has been executed

Example:

for (var i=0; i<5; i++)
  {
      x=x + "The number is " + i + "<br>";
  }
Copy the code

From the example above, you can see: 1 sets the variable (var I =0) before the loop begins. Define the conditions under which the loop runs (I must be less than 5). 3 increments a value (i++) each time a block of code has been executed.

2.for… in… Basic syntax for looping object properties:

for (var inObject) {code block executed}var person = {fname:"John".lname:"Doe".age:25}; 
var text = "";
var x;
for (x inperson) { text += person[x]; } Result: John Doe25
Copy the code

For (let I in arr) for (const v of arr)

The forEach() method is used to call each element of the array and pass the element to the callback function. ForEach () traversal method traverses all the elements of the number group, uses the callback function to operate on the array, and traverses the number group automatically, and cannot break out of the loop through break. It is uncontrollable and does not support return operation output. Return is only used to control whether the loop breaks out of the current loop

Note that forEach() does not perform callbacks on empty arrays.

Basic syntax:

array.forEach(function(currentValue, index, arr), thisValue)
Copy the code

ForEach () in ES6:

 let totalPrice = 0,
      totalNum = 0,
      allCheckd = true;
    cart.forEach(v= > {
      if (v.checked) {
        totalPrice += v.goods_price * v.num;
        totalNum += v.num;
      } else {
        allCheckd = false; }});// Callback uses arrow functions
Copy the code

4. Some () corresponding link: blog.csdn.net/qq_40190624… Every () and some () purpose: to determine whether all members of an array satisfy the specified test some: true is true

Example:

/** * Computes whether the fastener system of each computer in the array of objects is available
var computers = [
    {name:"Apple".ram:8},
    {name:"IBM".ram:4},
    {name:"Acer".ram:32},];var result= computers.every(function(computer){
   return computer.ram > 16
})
console.log(result)//false;
var some = computers.some(function(computer){
   return computer.ram > 16
})
console.log(some)//true;HTTPS://blog.csdn.net/qq_40190624/article/details/82533610
Copy the code

5. Every () blog.csdn.net/qq_40190624… The every () method must return true for all of them, even if there is one false; Every () and some () Purpose: To determine whether all members of an array satisfy the specified test every: a false is false

Example:

// Determine whether each person in the array is an adult, greater than 17, otherwise minor
var arr = [
            {name:'jerry'.sex:'man'.age:14},
            {name:'jack'.sex:'woman'.age:19},
            {name:'bill'.sex:'man'.age:18}]var every = arr.every(function(obj){  // Every false is false
            return obj.age > 17   
        })
        var some = arr.some(function(obj){   // Some true is true
            return obj.age >17
        })
        console.log(every,some)  //false true
Copy the code

Map () maps a new array from the current array. Unlike forEach and other traversal methods, a return statement in forEach has no effect. Map can change the value of the current loop and return a new array with changed values (map returns). Map () loops through an array, changing the value of the original array and returning a new array with the changed value, but map() returns.

Example:

let arr1 = [1.2.3];
let arr2 = arr1.map((value,key,arr) = > {
    console.log(value)    // 1,2,3
    console.log(key)      // 1, 2
    console.log(arr)      //[1,2,3] [1,2,3] [1,2,3] has several values and iterates through several arrays of itself
    return value * value;
})
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 4, 9]HTTPS://blog.csdn.net/weixin_44223007/article/details/98479489
Copy the code

You can also iterate over objects:

let products= [
			{ name: "马云".price: 200 },
			{ name: Ma Huateng.price: 140 },
			{ name: "Ma Dongmei".price: 20 },
			{ name: "马某".price: 10}]var newProducts= products.map(product= > {
		return {
			// Change the loop value to get a new array
			name: "* *" + product.name + "* *".price: product.price / 2
		};
});
console.log(newProducts)
/ * 0: {name: "ma * * * *", price: 100} 1: {name: "ma * * * *", price: 70} 2: {name: "dong-mei ma * * * *," price: 10} 3: {name: "** *", price: 5} */HTTPS://blog.csdn.net/weixin_44223007/article/details/98479489
Copy the code

7. Filter () filter() method, used to filter an array, returns a new array, filter() method in the loop to determine whether the element is true or false

Example:

let arr1 = [1.2.3];
let arr2 = arr1.filter((value,key,arr) = > {
    console.log(value)    // 1,2,3
    console.log(key)      // 1, 2
    console.log(arr)      / / [1, 2, 3]
    return value >= 3 ? false : true;     
})
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2]HTTPS://blog.csdn.net/weixin_44223007/article/details/98479489
Copy the code

Filter () can be used to remove nonconforming array elements

let arr = [1.2.3]
let newArr = arr.filter(item= > item>=3)  
console.log(newArr)/ / [3]
Copy the code

Filter () removes the empty string, undefined, and null

let arr = [' '.'1'.'2'.undefined.'3.jpg'.undefined]
let newArr = arr.filter(item= > item)
console.log(newArr) // arr=['1','2','3.jpg']
Copy the code

Filter Deduplicates the filter array

let arr = [1.2.2.3.4.5.5.5.6.6.6.6];
let newArr = arr.filter((x, index,self) = >self.indexOf(x)===index) 
console.log(newArr)
Copy the code

Filter () filters array objects

let arr = [
	    {a:'apple'.b:'bread'.c:'eat'},
	    {a:'banana'.b:'bread'.c:'don't eat'},
	    {a:'banana'.b:'apple'.c:'eat'},
	    {a:'apple'.b:'banana'.c:'don't eat'},]console.log(arr.filter(item= > item.a=== 'apple' ))
//[{a:' apple ',b:' bread ',c:' eat '},{a:' apple ',b:' banana ',c:' don't eat '}]
Copy the code

Note: If multiple criteria are filtered, you can add this type of judgment after item

item => (a? item.a === a :true) && (b? item.b === b :true) && (c? item.c === c :true)
Copy the code

The values of A, B and C need to be preset in advance

8. IndexOf () link: www.jianshu.com/p/14635c245… The indexOf() method returns the first occurrence of a specified string value in the string, or -1 if none is found

IndexOf () returns only strings in the specified search order, applied in the position of the first occurrence => This method returns -1 if the string value to be retrieved is not present

  1. grammar
stringObject.indexOf(searchvalue,fromindex)

// This method will retrieve the string stringObject from beginning to end to see if it contains the substring searchValue.
// Start the search at the fromindex of the string or at the beginning of the string (if fromindex is not specified).
// If a searchValue is found, the first occurrence of the searchValue is returned.
// Character positions in stringObject start at 0
Copy the code

IndexOf () Returns the position of an element in a string or array. (1) The use of string

let str = 'orange';
 
str.indexOf('o'); / / 0
str.indexOf('n'); / / 3
str.indexOf('c'); / / 1
Copy the code

(2) The use of array types

Array.indexof (item,start) returns the position of the element in the array, or - if it is not retrieved1. Item This parameter is mandatory. The search element start is optional. Specifies the location to retrieve, and its legal value is0To stringObject. Length -1.Copy the code

Example:

let arr = ['orange'.'2016'.'2016'];
 
arr.indexOf('orange'); / / 0
arr.indexOf('o'); / / 1

var arr = [1.2.3];
console.log(arr.indexOf(1));/ / 0
console.log(arr.indexOf(2));/ / 1
console.log(arr.indexOf(3));/ / 2
console.log(arr.indexOf(4));/ / 1
Copy the code

To find elements in an array, you can also use es6’s find() method

(3) The number type cannot be used

let num = 2016;
 
num.indexOf(2); //Uncaught TypeError: num.indexOf is not a function
Copy the code

If you must use this method for the number type, convert the value to a string. Example:

/ / simple
num = '2016';
num.indexOf(2); / / 0

/ / the general
num.toString().indexOf(2); / / 0

/ / the most concise
(' ' + num).indexOf(2); / / 0
Copy the code

3. Use indexOf() to delete an array:

/ / write one
var newArr =  [ ];
 arr.forEach(function(v){ // Use forEach loop to get all the values in the original array arr
            // In the new array, find the current value of the original array
            Newarr.indexof (v) If the result is -1
            // Prove that there is no data for the original array in the new array
 newArr.indexOf(v) 
    if(newArr.indexOf(v) === -1) {// Write this data to the new array
                newArr.push(v)
            }
        })
        console.log( newArr );

/ / write two
var arr = ['C'.'A'.'A'.'G'.'G'.'G'.'D']
        var newArr = []
        arr = arr.sort(function(a,b){
            return a > b
        }).forEach(function(n){
            if(newArr.indexOf(n) == -1){
                newArr.push(n)
            }
        })
        console.log(newArr);// ["A", "C", "D", "G"]

/ / writing three
var arr = ['a'.'c'.'b'.'d'.'a'.'b']
        var arr2 = [];
        for(var i = 0; i<arr.length; i++){if(arr2.indexOf(arr[i])<0){
                arr2.push(arr[i]);
            }
        }
        arr2.sort();
        console.log(arr2);//["a", "b", "c", "d"]
        The sort() method is the way to sort an array
        / / link: https://www.w3school.com.cn/js/jsref_sort.asp
Copy the code

9. FindIndex () link: m.runoob.com/jsref/jsref… 1. Grammar

array.findIndex(function(currentValue, index, arr), thisValue)
Copy the code

(1) The findIndex() method returns the location of the first element of an array passed in to test the condition. (2) findIndex() calls the function once for each element in the array:

  1. When an element in an array returns true on a test condition, findIndex() returns the index position of the element that matches the condition, and the subsequent value is not called.
  2. Returns -1 if no element matches the criteria

Note: findIndex() does not execute for an empty array. Note that findIndex() does not change the original value of the array. [Does not change the original array]

Example:

const bookArr=[
    {
        id:1.bookName:Romance of The Three Kingdoms
    },
    {
        id:2.bookName:"Water Margin"
    },
    {
        id:3.bookName:A Dream of Red Mansions
    },
    {
        id:4.bookName:Journey to the West}];var i=bookArr.findIndex((value) = >value.id==4);
console.log(i);/ / 3
var i2=bookArr.findIndex((value) = >value.id==100);
console.log(i2);// -1
Copy the code

10. The find () link: www.jianshu.com/p/1c15be16a… This method is mainly used to find the first array element that matches the criteria. Its argument is a callback function. In the callback function, you can write the condition for the element you are looking for, and when true, return the element. If there are no qualified elements, undefined is returned.

Example:

// Search the myArr array for elements with an element value greater than 4. The result is the element found
const myArr=[1.2.3.4.5.6];
var v=myArr.find(value= >value>4);
console.log(v);/ / 5

// If there are no matching elements, return undefined
const myArr=[1.2.3.4.5.6];
var v=myArr.find(value= >value>40);
console.log(v);// undefined
Copy the code

The callback function takes three arguments. Value: indicates the current array element. Index: indicates the current index. Arr: Array to be searched

Example:

// Find the element with index value 4
const myArr=[1.2.3.4.5.6];
var v=myArr.find((value,index,arr) = >{
    return index==4
});
console.log(v);/ / 5
Copy the code

Note: find() does not execute for an empty array. Note: find() does not change the original array value

11. Include () link: www.jb51.net/article/124…

In ES5, Array already provides indexOf to find the location of an element, and returns -1 if it does not exist. However, this function has two minor drawbacks when determining whether an Array contains an element. The first is that it returns -1 and the location of the element. Another problem is that you can’t tell if there are elements of NaN.

Example:

const arr1 = ['a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i'.'j'.'k'.NaN]
console.log('%s', arr1.indexOf(NaN))
// Result: -1
Copy the code

ES6 provides the array.includes () function to determine whether or not an element is included. It directly returns true or false to indicate whether the element is included or not, and is valid for NaN as well. NaN = true if there is an element in the array, false if there is no element

Example:

const arr1 = ['a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i'.'j'.'k'.NaN]
console.log('%s', arr1.includes('c'))//true
console.log('%s', arr1.includes('z'))//false
console.log('%s', arr1.includes(NaN))//true

// The second argument to the includes() function indicates the starting position of the decision.
const arr1 = ['a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i'.'j'.'k'.NaN]
console.log('%s', arr1.includes('d'.1))//true
console.log('%s', arr1.includes('d'.3))//true
console.log('%s', arr1.includes('d'.4))//false

// The second argument can also be negative, indicating the number from the right, but does not change the direction of the search, the search direction is still left to right
console.log('%s', arr1.includes('k', -1))//false
console.log('%s', arr1.includes('k', -2))//true
console.log('%s', arr1.includes('i', -3))//false

Copy the code

12. The set () can be used for object (array) to merge, to restore links: www.cnblogs.com/mahmud/p/10… Set () in ES6 allows you to select data that meets your criteria from an array of returned data.

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values. The Set itself is a constructor used to generate the Set data structure.

1. Array deduplication



[…new Set(arR)] is a deconstructed array that stores the non-repeating elements of arR into an array unique

2. Characters are deleted

In addition, Set is so powerful that it is easy to implement Union, intersection, and Difference using Set.

Set () in MDN: developer.mozilla.org/en-US/docs/…

The array.from () method converts a Set structure to an Array. We can write a special function that uses a de-weight function

Reprint link: www.cnblogs.com/jf-67/p/844…

The array.from () method converts an array-like object or traversable object into a real Array.

So what is an array-like object? The basic requirement for an array-like object is an object with a length attribute.

1. Convert an array-like object to a real array:

let arrayLike = {
    0: 'tom'.1: '65'.2: 'male'.3: ['jane'.'john'.'Mary'].'length': 4
}
let arr = Array.from(arrayLike)
console.log(arr) / / [' Tom ', '65' and 'male', [' Jane ', 'John', 'Mary']]
Copy the code

So what if the length attribute was removed from the code above? As it turns out, the answer will be an empty array of length 0.

The object has a length attribute, but instead of a numeric attribute, the object has a string name, as follows:

let arrayLike = {
    'name': 'tom'.'age': '65'.'sex': 'male'.'friends': ['jane'.'john'.'Mary'].length: 4
}
let arr = Array.from(arrayLike)
console.log(arr)  // [ undefined, undefined, undefined, undefined ]
Copy the code

The result is an array of length 4 with undefined elements

Important: To convert an array-like object into a real array, the following conditions must be met:
1. Array objects of this class must have a length attribute, which specifies the length of the array. If there is no length attribute, the transformed array is an empty array.
2. The property name of this array object must be a numeric or string number
Note: The property names of array objects of this class may or may not be quoted

2. Convert Set data into a real array:

let arr = [12.45.97.9797.564.134.45642]
let set = new Set(arr)
console.log(Array.from(set))  // [12, 45, 97, 9797, 564, 134, 45642]
Copy the code

Array.from can also take a second argument, similar to the map method of arrays, that is used to process each element and place the value in the returned Array. As follows:

let arr = [12.45.97.9797.564.134.45642]
let set = new Set(arr)
console.log(Array.from(set, item= > item + 1)) // [13, 46, 98, 9798, 565, 135, 45643]
Copy the code

3. Convert strings to arrays:

let  str = 'hello world! ';
console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
Copy the code

The array. from argument is a real Array:

console.log(Array.from([12.45.47.56.213.4654.154]))
Copy the code

In the fourth case, array. from returns an identical new Array