一、数组扩展之扩展运算符
1.扩展运算符
- 扩展运算符(spread)是三个点(…)。将一个数组转为用逗号分隔的参数序列。
<script>var arr = [10,23,45,6,7];//以前获取数组中的每个元素for(let i = 0;i<arr.length;i++){console.log(arr[i]);}//有了扩展运算符之后console.log(...arr)</script>
用途:
1.替代函数的apply方法
- 由于扩展运算符可以展开数组,所以不再需要 appy方法,将数组转为函数的参数了。
<script>var arr = [10,23,45,6,7];//以前获取数组中的每个元素for(let i = 0;i<arr.length;i++){console.log(arr[i]);}//有了扩展运算符之后console.log(...arr) //求数组中的最大值//以前console.log(Math.max.apply(null,arr))//有了...之后console.log(Math.max(...arr))</script>
2. 合并数组
<script>var arr1 = [10,23,45,6,7];var arr2 = [34,34,56,43];//合并数组//以前console.log(arr1.concat(arr2))//有了...之后console.log([...arr1,...arr2])</script>
二、新增方法
2.1 Array.from()
-
Array.from()方法用于将类数组转为真正的数组.
-
1)arguments
<body><script>//类数组,伪数组,只能使用数组的读取方式和length属性,不能使用数组方法function add(){ //add()没有参数console.log(arguments) //这里用arguments可以将下面14行的参数传进来}add(10,20,30)</script> </body>
2)元素集合
<body><h3>标题1</h3><h3>标题2</h3><h3>标题3</h3><script>let titles = document.querySelectorAll("h3");console.log(titles);console.log(titles[0]);console.log(titles[1]);console.log(titles[2]);</script> </body>
3)类似数组的对象
<script>var user = {"0":"zhagnsan","1":20,"3":3}</script>
用法:
<body><h3>标题1</h3><h3>标题2</h3><h3>标题3</h3><script>//类数组,伪数组,只能使用数组的读取方式和length属性,不能使用数组方法function add() { //add()没有参数console.log(arguments); //这里用arguments可以将下面14行的参数传进来var result = Array.from(arguments);result.push(40);console.log(result)}add(10, 20, 30)let titles = document.querySelectorAll("h3"); console.log(Array.from(titles));var user = {"0":"zhagnsan","1":20,"3":3}console.log(Array.from(user)); </script> </body>
2.2 Array.of()
- Aray.of() 方法用于将一组值,转换为数组.