文章目录
1.扩展运算符…
2.Array.from()
将两类对象转为真正的数组:类数组(querrySelectAll)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)
类数组
1.赋给length属性的对象
//将类数组转化为真正的数组
let k={
0:'a',
1:'b',
length:2 //没有length属性就不行
}
console.log(Array.from(k)); //['a', 'b']
2.字符串也有length属性,它也是类数组
let str='hello';
console.log(Array.from(str)); // ['h', 'e', 'l', 'l', 'o']
3.参数如果是真正的数组 则返回一个全新数组
let s1=[1,2,3];
let s2=Array.from(s1);
console.log(s2==s1); //false
3.Array.of()
将一组值,转换为数组
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
这个方法的主要目的,是弥补数组构造函数Array()的不足。因为参数个数的不同,会导致Array()的行为有差异。
只有当参数个数不少于 2 个时,Array()才会返回由参数组成的新数组
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
4.find() 和 findIndex()
find方法,用于找出第一个符合条件的数组成员
var result1=[1,2,3,4].find(function (item) {
return item%2==0;
})
console.log(result1); //2
findIndex方法,返回第一个符合条件的数组成员的位置。
如果所有成员都不符合条件,则返回-1
var result1=[1,2,3,4].findIndex(function (item) {
return item%2==0;
})
console.log(result1); //1
5.fill() 填充数组
使用给定值,填充一个数组
console.log(new Array(5).fill('a')); //['a', 'a', 'a', 'a', 'a']
fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
['a', 'b', 'c'].fill(7, 1, 2) // ['a', 7, 'c']
6.数组实例的 entries(),keys() 和 values()
Set,Map,Object中都有这些方法
entries(),keys()和values()——用于遍历数组。
它们都返回一个遍历器对象,可以用for…of循环进行遍历
唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。
let yes=[1,2,3,4];
console.log(yes.keys()); //Array Iterator {}
console.log(yes.values()); //Array Iterator {}
console.log(yes.entries()); //Array Iterator {}
let yes=[1,2,3,4];
for(let key of yes.keys()){
console.log(key); //0 1 2 3
}
for(let key of yes.values()){
console.log(key); //1 2 3 4
}
for(let [key,value] of yes.entries()){
console.log(key,value);
//0 1
//1 2
//2 3
//3 4
}
7.includes()
console.log([1, 2, 3].includes(1)); //true
console.log([1, 2, 3].includes(1,1)); //false 从1号索引开始找
8.flat()
将嵌套的数组“拉平”,变成一维的数组。
该方法返回一个新数组,对原数据没有影响
//默认只能拉平一层
console.log([1, 2, [3, 4]].flat()); //[1, 2, 3, 4]
//如果拉平多层 设置层数
console.log([1, 2, [3, [4, 5]]].flat(2)); // [1, 2, 3, 4, 5]
//如果层数太多 设置Infinity
console.log([1, 2, [3, 4, [5, 6, [7, 8]]]].flat(Infinity)); //[1, 2, 3, 4, 5, 6, 7, 8]
9.reduce()
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。对空数组是不会执行回调函数的。
1.计算数组总和
var num = [1,2,3,4,5];
var res = num.reduce(function(total,num){
return total+num;
//return total + Math.round(num);//对数组元素四舍五入并计算总和
},0);
console.log(res); //15
//num.reduce((total,num) => total += num, 0);
//没有初始值initialValue(即上面例子中的0),当数组为0时会抛出异常提示reduce函数没有初始值,所以为兼容性一般加上initialValue
2.合并二维数组
var red = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
}, []);
console.log(red); //[0, 1, 2, 3, 4, 5]
3.统计一个数组中有多少个不重复的单词
reduce()函数