What do these three dots in React do?

前端 未结 29 2662
不思量自难忘°
不思量自难忘° 2020-11-21 23:53

What does the ... do in this React (using JSX) code and what is it called?



        
29条回答
  •  梦谈多话
    2020-11-22 00:36

    Three dots ... represents Spread Operators or Rest Parameters,

    It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected.

    • Merge two arrays

    var arr1 = [1,2,3];
    var arr2 = [4,5,6];
    
    arr1 = [...arr1, ...arr2];
    console.log(arr1);  //[1, 2, 3, 4, 5, 6]

    • Copying array:

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

    Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

    • Add values of one array to other at specific index e.g 3:

    var arr1 = [4,5]
    var arr2 = [1,2,3,...arr1,6]
    console.log(arr2);	// [1, 2, 3, 4, 5, 6]

    • When calling a constructor with new:

    var dateFields = [1970, 0, 1];  // 1 Jan 1970
    var d = new Date(...dateFields);
    
    console.log(d);

    • Spread in object literals:

    var obj1 = { foo: 'bar', x: 42 };
    var obj2 = { foo: 'baz', y: 13 };
    
    var clonedObj = { ...obj1 };
    console.log(clonedObj);	//{foo: "bar", x: 42}
    
    var mergedObj = { ...obj1, ...obj2 };
    console.log(mergedObj);	//{foo: "baz", x: 42, y: 13}

    Note that foo property of obj1 has been overwritten by obj2 foo property

    • As a rest parameter syntax which allows us to represent an indefinite number of arguments as an array:

    function sum(...theArgs) {
      return theArgs.reduce((previous, current) => {
        return previous + current;
      });
    }
    
    console.log(sum(1, 2, 3));	//6
    console.log(sum(1, 2, 3, 4));	//10

    Note:Spread syntax (other than in the case of spread properties) can be applied only to iterable objects: So following will throw error

    var obj = {'key1': 'value1'};
    var array = [...obj]; // TypeError: obj is not iterable

    Reference1

    Reference2

提交回复
热议问题