Application of spread operator in arrays and objects

… ES6 spread operator

1. The spread operator can expand data.
2. The spread operator cannot be used alone to expand an array. It can be used in parameters to convert the parameter array into a parameter list.
3. If the spread operator is followed by a variable, then a separate extra array is accepted and placed into the array.

1. Application of spread operator in arrays

1. Traverse the array

	var arr = [1, 2, 3, 4]
    console.log(...arr);

2. Can be used as an array parameter

	var arr = [1, 2, 3, 4]
	var numArr = ['a', ...arr, 'b']
    console.log(numArr);

3. You can perform deep copies of arrays

	var arr = [1, 2, 3, 4]
	var arrA = [...arr]
    console.log(arrA);
    arrA.unshift(0)  // 给arrA数组添加元素
    console.log(arrA);
    console.log(arr);

4. Can be used as parameters in functions

 	var arr = [1, 2, 3, 4]
 	function fn(x, ...y) {
    
    
        console.log(x);
        console.log(...y);
    	}
    	fn(...arr)

5. Use it with destructuring assignment

	let [a, ...b] = [1, 2, 3, 4]
    console.log(a);
    console.log(b);

6. You can convert pseudo arrays into real arrays

	var str = '我们真好'
    	console.log(Array.from(str));  // Array.from()也可以将伪数组转化为真正的数组
    	console.log([...str]);

2. Application of expanders in objects

1. Traverse objects

var obj = {
    
    
        name: 'name',
        age: 18,
        sex: '男'
    }
    console.log({
    
     ...obj});

2. Assign default values ​​to objects

 var obj_1 = {
    
    
        a: 1,
        b: 2
    }
    var obj_2 = {
    
    
     ...obj_1,
        b: 3
    }
    console.log(obj_2);

The same properties in the merged objects will be overwritten

3. Merge objects

let obj1 = {
    
    a:1)
let obj2 = {
    
    b:2},
let obj3 ={
    
    ...obj1,...obj2);
console.log(obj3)

4. If the spread operator is followed by a string, it will automatically be converted into an array-like object, so the returned object is not an empty object.

console.log({
    
    ...'hello'});//{ '0': 'h', '1': 'e', '2': 'l', '3': 'l', '4': 'o' }

3. If the spread operator is not followed by an object, it will be automatically converted into an object. Since the object has no properties of its own, an empty object is returned.

console.log({
    
    ...1});//{}
console.log({
    
    ...true});//{}
console.log({
    
    ...undefined});//{}
console.log({
    
    ...null});//{}

Guess you like

Origin blog.csdn.net/qq_52654932/article/details/130273381