只用of而不是in?
例如:
for(var i of [1,5,3,4]) {
console.log(i)
}
返回:
1
5
3
4
编辑 1:
可能与此重复:For-each over an array in JavaScript?
编辑 2:
这是一个使用 JSON 对象的示例:
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push({
id : i,
func : function () {
alert("hello world\nfrom " + this.id);
}
});
}
for (var i of arr) {
console.log(i.id);
i.func();
}
编辑 3:
由于对象和数组的工作方式,您不能将 of 直接应用于对象。
数组是一个单独的、不相关的值的列表,它们彼此或保存它们的数组一无所知。没有“this”,因为每个都是自己的独立变量。
然而,对象不是一组对自变量的引用,而是包含在对象内的一组函数和变量的作用域。
因此,您不能在逻辑上使用 of,因为这会将单个键作为独立变量引用,即使它们只存在于对象中。
但是,您可以使用类似这样的方法来填充解决方案:
var master = {};
for (var i = 0; i < 10; i++) {
master[i] = {
id : Math.round(Math.random() * 1000),
func : function () {
alert("hello world\nfrom " + this.id);
}
}
}
//Polyfill to get elements based upon the IN loop
Object.prototype.getValues = function (obj) {
if (typeof obj === "undefined") {
obj = this;
}
var values = [];
for (var i in obj) {
if (i != 'getValues') {
values.push(obj[i]);
}
}
return values;
}
//Loop through the values delivered by the polyfill
for (var a of master.getValues()) {
console.log(a);
}
此方法为所有对象提供了一个标准方法,以生成对其每个内部属性的引用,然后我们只需返回数组。
然后该数组包含对每个基础属性的单独引用,允许您在 of 循环中循环它们。
顺便说一句,上面的代码应该在控制台中返回一个对象列表,如下所示:
Object { id=723, func=function(), getValues=function()}
Object { id=857, func=function(), getValues=function()}
Object { id=8, func=function(), getValues=function()}
Object { id=160, func=function(), getValues=function()}
Object { id=573, func=function(), getValues=function()}
Object { id=959, func=function(), getValues=function()}
Object { id=512, func=function(), getValues=function()}
Object { id=532, func=function(), getValues=function()}
Object { id=840, func=function(), getValues=function()}
Object { id=72, func=function(), getValues=function()}
从这里你可以这样做:
for (var a of master.getValues()) {
a.func();
}
访问对象属性。