How to iterate over a JavaScript object?

后端 未结 18 1961
失恋的感觉
失恋的感觉 2020-11-21 22:52

I have an object in JavaScript:

{
    abc: \'...\',
    bca: \'...\',
    zzz: \'...\',
    xxx: \'...\',
    ccc: \'...\',
    // ...
}

I

18条回答
  •  轮回少年
    2020-11-21 23:25

    If you wanted to iterate the whole object at once you could use for in loop:

    for (var i in obj) {
      ...
    }
    

    But if you want to divide the object into parts in fact you cannot. There's no guarantee that properties in the object are in any specified order. Therefore, I can think of two solutions.

    First of them is to "remove" already read properties:

    var i = 0;
    for (var key in obj) {
        console.log(obj[key]);
        delete obj[key];
        if ( ++i > 300) break;
    }
    

    Another solution I can think of is to use Array of Arrays instead of the object:

    var obj = [['key1', 'value1'], ['key2', 'value2']];
    

    Then, standard for loop will work.

提交回复
热议问题