1.for循环:使用最平凡,但注意使用let定义变量,原因上篇文章已说明
for (let index = 0; index < array.length; index++) { }
2.for...in
遍历:用于遍历对象的可枚举属性(包括它的原型链上的可枚举属性),for/in
主要用于遍历对象(最常用于调试),不建议用来遍历数组。
原因:因为迭代的顺序是依赖于执行环境的,所以数组遍历不一定按次序访问元素。因此当迭代访问顺序很重要的数组时,最好用整数索引去进行for
循环(或者使用 Array.prototype.forEach()
或 for...of
循环)。
//遍历对象
let obj = {
name: 'zhang',
age: 28
};
Object.getPrototypeOf(obj).sex = '男'
for (const key in obj) {
console.log(key);//打印: name age sex
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {//对象的hanOwnProperty属性我们会在原型中讲解
console.log(key);//打印: name age
}
}
//遍历数组
let arr = ['item1', 'item2', 'item3'];
for (let key in arr) {
console.log(key);
}
3.for of遍历:用来遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合), NodeList(DOM节点集合)等可迭代的数据结构。
//迭代Array
let arr = [10, 20, 30];
for (let value of arr) {
value += 1;
console.log(value);
}// 11 21 31
//如果你不想修改语句块中的变量 , 也可以使用const代替let。
let arrs = [10, 20, 30];
for (const value of arrs) {
console.log(value);
}//10 20 30
//迭代String
let strs = "boo";
for (let value of strs) {
console.log(value);
}// "b" "o" "o"
//迭代Map
let map = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let entry of map) {
console.log(entry);
}// ["a", 1] ["b", 2] ["c", 3]
for (let [key, value] of map) {
console.log(value);
}// 1 2 3
//迭代 Set
let set = new Set([1, 2, 3]);
for (const value of set) {
console.log(value);
}
//遍历DOM元素
<body>
<ul>
<li></li>
<li></li>
</ul>
</body>
let lis = document.querySelectorAll("li");
for (const li of lis) {
li.addEventListener("click", function () {
this.style.backgroundColor = "red";
});
}
4.forEach
forEach
使函数作用在每个数组元素上,但是没有返回值。
下面例子是截取标签的五个字符。
let lessons = [
{title: '媒体查询响应式布局',category: 'css'},
{title: 'FLEX 弹性盒模型',category: 'css'},
{title: 'MYSQL多表查询随意操作',category: 'mysql'}
];
lessons.forEach((item, index, array) => {
item.title = item.title.substr(0, 5);
});
console.log(lessons);