简体   繁体   中英

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

Let's say I have the following code:

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

Is there a way to get the current property of the object without having to store it in a variable like that:

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

The first piece of code is disturbing to look at, while the second one needlessly uses more memory. Is there a way to avoid both problems at once?

Just use of instead of in ?

For instance:

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

Returns:

1
5
3
4

EDIT 1:

May be duplicate of this: For-each over an array in JavaScript?

EDIT 2:

Here is an example using JSON objects:

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

EDIT 3:

You can't apply of directly to objects because of the way objects and arrays work.

An array is a list of individual, unrelated values that knows nothing of eachother or the array that holds them. There is no "this" as each are their own independent variable.

An object however is not a set of references to independent variables but a scope for a set of functions and variables that are contained WITHIN the object.

Therefore you can't logically use of because that would reference the individual keys as standalone variables, even though they only live within the object.

However you could polyfill a solution for this using something like this:

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

This method gives a standard method on all objects to generate a reference to each of their inner properties and then we simply return the array.

That array then contains individual references to each underlying property, allowing you to loop over them in an of loop.

By the way, the code above should return a list of objects in the console looking like this:

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

From here you could just do:

for (var a of master.getValues()) {
    a.func();
}

To access the object properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM