Array
在ES6中新增了很多实用的API,方便开发者对Array的操控性更强,如for…of、from、of、find、findIndex等。
1. 数组遍历
关于数组的遍历,我们从最原始的for循环遍历数组到ES5遍历数组的API多了起来,其中forEach、every等来实现数组的遍历,到ES6则又加入了for…of API来遍历数组。
// 第一种.for循环
const arr = [1, 2, 3, 4, 5]
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 2) {
break
}
console.log(arr[i])
}
// 第二种.foreach
arr.forEach(function (item) {
console.log(item)
})
// 两种方法,
// 1.书写上看:forEach相对简单;
// 2.for语句中可以使用break、continue关键字,forEach中则会报错“语法不支持”
// 第三种.every
arr.every(function (item) {
console.log(item)
if (item === 2) {
// return false 相当于 for循环中的break
return false
}
if (item === 3) {
// 相当于 for循环中的continue效果
} else {
console.log(item)
}
return true
})
// 要使数组全部返回,需要加return true;函数默认返回值为false; 受控制
// 第四个.for in 是为对象Object设置的 可以使用continue"两个=="才可有效果,因为本质是Object,index是字符串,两个==只检查值不检查类型
arr.a = 8
for (let index in arr) {
// if (index == 2) {
// continue
// }
if (index * 1 === 2) {
continue
}
console.log(index, arr[index])
}
// es6新增 for of 重点介绍:
for (variable of iterable) {
}
//这个伪代码,of 后面是 iterable 既不是 for 循环规定的 array,也不是 for…in 规定的 Object,而是 iterable。如果查查 iterable 的含义就很直观的感受到 for…of 遍历的是一切可遍历的元素(数组、对象、集合)等,不要小瞧这个功能,因为在 ES6 中允许开发者自定义遍历,换句话说任何数据结构都可以自定义一个遍历,这个遍历是不能被 for、for…in 理解和实现的。