如何轻松获取Javascript for loop的当前迭代属性

How to easily get the current iteration property of a Javascript for loop?

本文关键字:迭代 属性 loop 何轻松 获取 Javascript for      更新时间:2023-09-26

假设我有以下代码:

for(var k in objectWithVeryLongName){
    objectWithVeryLongName[k].something();
    objectWithVeryLongName[k].otherSomething();
    objectWithVeryLongName[k].thirdSomething();
    ...
    objectWithVeryLongName[k].nthSomething();
}

有没有办法获取对象的当前属性,而不必将其存储在这样的变量中:

var prop;
for(var k in objectWithVeryLongName){
    prop = objectWithVeryLongName[k];
    prop.something();
    prop.otherSomething();
    ...
    prop.nthSomething();
}
第一段代码

令人不安,而第二段代码则不必要地使用更多内存。有没有办法同时避免这两个问题?

只是使用而不是in

例如:

for(var i of [1,5,3,4]) {
  console.log(i)
}

返回:

1
5
3
4

编辑 1:

可能是重复的:在 JavaScript 中的数组上为 for-each?

编辑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:

由于对象和数组的工作方式,您无法直接将 应用于对象。

数组

是单个、不相关的值的列表,这些值彼此或保存它们的数组一无所知。没有"这个",因为每个都是自己的自变量。

然而,对象不是对自变量的一组引用,而是包含在对象中的一组函数和变量的作用域。

因此,您不能在逻辑上使用 ,因为这会将各个键作为独立变量引用即使它们仅存在于对象中。

但是,您可以使用如下所示的内容填充解决方案:

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();
}

访问对象属性。