关键词:数组
array.form
我们知道document.getElementsByTagName
获取的是一个集合,它有有长度,能遍历,但它不是纯粹的数组:
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
var divs = document.getElementsByTagName('div');
var div = [].slice.call(divs);
console.dir(div); //Array
console.dir(divs); //HtmlCollection
ES6提供了array.form
方法把集合转为数组
var eles = Array(divs);
console.log(eles);
var eles = Array.from(divs);
console.log(eles); // [div, div, div, div, div, div]
array from
不仅可以转集合,还可以转换字符串
var str = "sdsdss";
console.log(Array.from(str)); // ["s", "d", "s", "d", "s", "s"]
array.of
我们用new Array
建立数组时候,如果只输入一个数据,数组会把它默认为长度
var arr = new Array(5);
console.log(arr); // [] length:5
var arr = new Array(5,6,7); // [5, 6, 7]
console.log(arr);
这个时候用array.of
就可以解决
var arr = Array.of(5);
console.log(arr); //[5]
find()函数
var arg = [1,2,3,4,5]
var n = arg.find(function(value,index){
return value > 3;
});
console.log(n); //4
var nn = arg.findIndex(function(value,index){
return value > 3; // 3
});
console.log(nn);
如果数组是字符串会返回什么?
var arg = ["小明","小强","小李","小王","小张"];
var n = arg.find(function(value,index){
return value > 3;
});
console.log(n); //undenfined
var nn = arg.findIndex(function(value,index){
return value > 3; // 3
});
console.log(nn); // -1
fill()函数
替换数组中对应区间的值
语法:fill ( range,start,end )
var rr = [8,8,8,8,8,8];
rr.fill(6,2,5); // [8, 8, 6, 6, 6 ,8]
console.log(rr);
for...of
感觉就是个语法糖
var arr = ["22","33","44","55"];
for(var [key,value] of arr.entries()){
console.log(key,value);
}
for(var key of arr.keys()){
console.log(key);
}
for(var value of arr){
console.log(value);
}
// 返回结果
0 "22"
1 "33"
2 "44"
3 "55"
0
1
2
3
22
33
44
55