js_遍历(不同的for) for & for of & for in & forEach 相关实例
基础for
for
循环与 C 和 Java 中的相同:使用时可以在一行代码中提供控制信息。
for
for (var i = 0; i < 5; i++) {
// 将会执行五次
}
增强for
JavaScript 也还包括其他两种重要的 for 循环:
- for of
- for in
for of
for (let value of array) {
// do something with value
}
for in
常用于js对象的属性(字段)遍历
for
…in
:
for (let property in object) {
// do something with object property
}
遍历数组
for
可以通过如下方式遍历一个数组:
for (var i = 0; i < a.length; i++) {
// Do something with a[i]
}
for of
- ES2015 引入了更加简洁的
for
…of
循环,可以用它来遍历可迭代对象,例如数组:
for (const currentValue of a) {
// Do something with currentValue
}
for in
不推荐此方式遍历数组
- 遍历数组的另一种方法是使用
for...in
循环, 然而这并不是遍历数组元素而是数组的索引。 - 注意,如果哪个家伙直接向
Array.prototype
添加了新的属性,使用这样的循环这些属性也同样会被遍历。 - 所以并不推荐使用这种方法遍历数组:
for (var i in a) {
// 操作 a[i]
}
forEach
ECMAScript 5 增加了另一个遍历数组的方法,forEach
["dog", "cat", "hen"].forEach(function(currentValue, index, array) {
// 操作 currentValue 或者 array[index]
});
如果想在数组后追加元素,只需要:
a.push(item);
forEach() and push()
除了 forEach()
和 push()
,Array(数组)类还自带了许多方法。建议查看 Array 方法的完整文档。
例子1
array = [1, 2, 3, 4];
names_array = ["a", "b", "c", "d",];
object = {
name: "John",
age: 30,
city: "New York"
};
/* baisc for */
for (var i = 0; i < 5; i++) {
// 将会执行五次
console.log(i);
}
/* for of遍历可迭代对象 */
for (let value of names_array) {
console.log(value);
}
for (let value of array) {
// do something with value
console.log(value);
}
/* for in遍历key of object /index of array */
// 检查对象的所有字段(key)
for (let property in object) {
// do something with object property
console.log(property, ':', object[property]);
}
for (let index in names_array) {
console.log(index, ':', names_array[index]);
}
/* forEach */
names_array.forEach(element => {
console.log(element);
});
例子2(demo codes2)
let list1 = [11, 22, 33, 44];
let list2 = [];
const demoOfForEach = () => {
list1.forEach(
(item) => {
item += "miniProgram";
list2.push(item);
}
);
console.log(list1, `expected no change in list1`);
console.log(list2, `expected changes`);
};
const demoOfMap = () => {
let list3 = list1.map(
(item) => {
{
return `${item}miniProgaming`;
}
}
);
console.log(`${list3}`);
};
const demoOfForOf = () => {
console.log(`this is list3:${list3}`);
/* demo in for */
console.log(`demo forOf`, `;👌element of the list are expected to print out `);
for (const item of list1) {
console.log(item);
}
};
/* demo of for of */
const demoOfForIn = () => {
console.log(`demo forIn`, `;👌index is expected to be print out.`);
for (const prop in list1) {
console.log(prop);
}
};
const list10 = [7, 8, 9];
const demoOfExpend = () => {
const newList = [...list1, ...list10];
const size = newList.length;
console.log(`${newList}`);
console.log(`length:${newList.length}`);
};
/* test: */
// demoOfForEach();按需调用相应函数查看结果
demoOfExpend();