返回

ES6数组的扩展

发布时间:2022-10-31 15:45:19 266

在ES6中,给数组添加很多新API,方便我们更简单操作数组。

扩展运算符

在实际的写法中,用三个点来表示,将数组转化为用逗号分隔的参数序列,也就是说扩展运算符可以展开数组。

const arr = [5, 92, 65, 2];
console.log(...arr);// 5,92,65,2

这个扩展运算符在给函数传参时比较常见,可以一次性将整个数组作为参数传给函数。

 

在ES6之前,我们时通过使用apply方法来,将数组转化为函数参数的。

function test(x, y, z) {
console.log("x===", x);
console.log("y===", y);
console.log("z===", z);
}

test.apply(null, arr);
console.log("================================")

test(...arr);

除此之外,扩展运算符还可以合并数组、解构赋值等!

 

Array.from()

这个方法是将两种对象转化为真正的数组:

1、类似数组的对象;

2、可遍历的对象;

const str = {
"0": "duxin",
"1": 18,
length: 2
}
// ES5的写法
console.log([].slice.call(str));
//ES6的写法
console.log(Array.from(str));

/**
* Array.of()
* 将一组数字转化为数组
*
* 跟定义数组的Array()或者new Array()相似,但是使用Array()来构造数组的时候,存在着一些不足,Array()入参的个数不同时,Array()执行中会存在一些差异
*/


console.log("------------Array.of()------------")

const arr1 = Array();
console.log(arr1); // []

const arr2 = Array(5);
console.log(arr2); //[<5 empty items>]

const arr3 = Array(1, 2, 3, 4, 5, 6, 7, 90);
console.log(arr3); // [ 1, 2, 3, 4, 5, 6, 7, 90 ]


const arr4 = Array.of(1);
console.log(arr4); // [1]


/**
* find()、findIndex()
* 查找数组中第一个符合条件的数组成员
*
* find(),返回符合条件的第一个数组成员
*
* findIndex(),返回符合条件的第一个数组成员的位置,也就是下标
*/

const findArr = [2, 3, 5, 6, 7, 8, 9, 10];
const targetArr = findArr.find((item) => {
return item % 2 == 0
});
const targetArr1 = findArr.findIndex((item) => {
return item % 2 == 0
});
console.log("===============find和findIndex===========");
console.log(targetArr); // 2
console.log(targetArr1);//0



/**
* includes(),返回一个布尔值,表示数组是否包含了目标数值
*/


const includeArr = [32, 43, 1, 34, 100];
console.log(includeArr.includes(2)); // false
console.log(includeArr.includes(100)); // true


/**
* 数组的空位指的是数组某一个位置没有任何的值,但是空位并不等于undefined,一个位置的值等于undefined,因为undefined也是一个数值。
*/

console.log(Array(5));// 构造出来的数组的每一个位置都是没有任何值



/**
* forEach()、filter()、every()、some()会跳过空位
*
* map()页也会跳过空位,但是保留这个值
*
* join()、toString()会把空位当做是undefined,undefined和null会被处理为空的字符串
*
*
* 在ES6中会把数组的空位转为undefined,如常用的扩展运算符(...),就是将数组的空位转为undefined
*
* entries()、keys()、values()、findIndex()、find()也会自动将数组的空位转为undefined
*/

const emptyArr = [1, , 23];
console.log(...emptyArr); // 1 undefined 23

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
微信小程序button修改样式无效 2022-10-31 15:06:43