Home > Article > Web Front-end > Introducing the common methods of spread operator in JavaScript
Personal understanding of...common methods
...as an expansion operation The symbol
refers to the expansion here for arrays or strings or pseudo-arrays (similar to arrays, you can use subscripts to take out each item, and there is an overall The extension of the length attribute data (hereinafter referred to as the traversable object) means to take out each item in the array and separate it with (when used, it is separated by spaces if printed separately) .
<script> let arr = [ 5, "str", [1,2,3], ["hello","world"], ]; function fn(arr){ console.log(...arr); return [...arr] } function fo(...arr){ console.log(arr); } // function foo(arr){ // return ...arr; // Expression expected. // } console.log(fn(arr)); // 5 "str" (3) [1, 2, 3] (2) ["hello", "world"] // (4) [5, "str", Array(3), Array(2)] // 外面的[]去掉了,但是里面的[1,2,3]、["hello","world"]的[]没有去掉 </script>
// 第一种所有参数都未知function aa(...arr){ console.log(arr);}aa(5,"sss",22) // (3) [5, "sss", 22] => 结果是一个数组// 第二种,有两个已知参数function ff(a,b,...arr){ console.log(arr)}ff(2,3,"str","111") // (2) ["str", "111"] => 结果是一个数组
You can use str.split("") or […str ]
Because it can display the traversable object by removing [] from the array, and it can be used on pseudo arrays, so it is easy to understand pseudo arrays. After use, after converting the form of the pseudo array, adding [] will become a real array, and you can call the method of the real array. => […arr.]
Since it uses a loop on a traversable object, it will not change the original array, but will make a shallow clone operation, so it can be used for shallow copies of arrays. => […arr]
<script> // 简单的二维数组(一个数组里面又套了一个数组 => 二维) let arr = [ 5, "str", [1,2,3], ["hello","world"], ]; // 三维数组(一个数组里面套一个数组,里面又套一个数组) let arr1 = [ 5, "str", [ 1,2,3, ["ccc","dddd"] ], ["hello","world"], ]; function flatten(arr){ return [].concat(...arr); } function flatten1(arr){ return [].concat(...arr.map(x => Array.isArray(x) ? flatten1(x) : x)); } console.log(flatten(arr)); // (7) [5, "str", 1, 2, 3, "hello", "world"] console.log(flatten1(arr)); // (7) [5, "str", 1, 2, 3, "hello", "world"] console.log(flatten(arr1)); // (8) [5, "str", 1, 2, 3, Array(2), "hello", "world"] console.log(flatten1(arr1)); // (9) [5, "str", 1, 2, 3, "ccc", "dddd", "hello", "world"] </script>
It can be seen from the above that when the array structure is very simple (two-dimensional), the spread operator can solve the array inside and Use concat for splicing. But when the array is multi-dimensional, it cannot solve the deeper array. It needs to use the spread operator and recursion to achieve this.
Recommended study: "javascript basic tutorial"
The above is the detailed content of Introducing the common methods of spread operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!