JS 中forEach,for in、for of用法实例总结
作者:书香水墨
这篇文章主要介绍了JS 中forEach,for in、for of用法,结合实例形式总结分析了JS 中forEach,for in、for of的基本功能、使用方法与相关注意事项,需要的朋友可以参考下
一、forEach
1.1 遍历数组
var array = [1,2,3,4,5,6];
/**
* currentValue 当前元素
* index 当前元素的索引值
* arr 当前元素所属的数组对象
**/
array.forEach(function(currentValue, index, arr) {
console.log("index: " + index + "; currentValue: ", currentValue);
});1.2 遍历对象
var object = {"a":1, "b":2, "c":3};
/**
* currentValue 当前元素
* index 当前元素的索引值
* arr 当前元素所属的数组对象
**/
Object.keys(object).forEach(function(currentValue, index, arr) {
console.log("index: " + index + "; currentValue: ", currentValue);
});二、for in
2.1 遍历数组
var array = [1,2,3,4,5,6];
for (var index in array) {
console.log("index: " + index + "; currentValue: ", array[index]);
}2.2 遍历对象
var object = {"a":1, "b":2, "c":3};
for (var index in object) {
console.log("index: " + index + "; currentValue: ", object[index]);
}三、for of
3.1 遍历数组
var array = [1,2,3,4,5,6];
for (var varlue of array) {
console.log("currentValue: ", varlue);
}3.2 遍历对象
for of不能直接遍历数组,需要为对象增加 Symbol.iterator 属性
3.2.1 方法一
var obj = {
a:1,
b:2,
c:3
};
obj[Symbol.iterator] = function(){
var keys = Object.keys(this);
var count = 0;
return {
next(){
if(count < keys.length) {
return {value:obj[keys[count++]], done:false};
}else{
return {value:undefined, done:true};
}
}
}
};
for(var k of obj){
console.log(k);
}3.2.2 方法二使用ES6 function*()
var obj = {
a:1,
b:2,
c:3
};
obj[Symbol.iterator] = function*(){
var keys = Object.keys(obj);
for(var k in keys){
yield [k, keys[k]]
}
};
for(var [k, v] of obj){
console.log(k, v);
}感兴趣的朋友可以使用本站在线工具:http://tools.jb51.net/code/HtmlJsRun 测试上述代码运行效果!
