我在JavaScript中有一个对象:

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

我想用一个for循环来获取它的属性。我想要迭代它的部分(不是所有的对象属性一次)。

对于一个简单的数组,我可以用一个标准的for循环来做:

for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last

但是如何对对象进行处理呢?


当前回答

<script type="text/javascript">
// method 1
var images = {};
images['name'] = {};
images['family'] = {};
images[1] = {};
images['name'][5] = "Mehdi";
images['family'][8] = "Mohammadpour";
images['family']['ok'] = 123456;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][23] = 2602;

for (const [key1, value1] of Object.entries(images)){
    for (const [key2, value2] of Object.entries(value1)){
        console.log(`${key1} => ${key2}: ${value2}`);
    }
}


console.log("=============================");

// method 2
var arr = [];
for(var x = 0; x < 5; x++){
     arr[x] = [];    
     for(var y = 0; y < 5; y++){ 
         arr[x][y] = x*y;    
     }    
 }

for(var i = 0; i < arr.length; i++) {
    var cube = arr[i];
    for(var j = 0; j < cube.length; j++) {
        console.log("cube[" + i + "][" + j + "] = " + cube[j]);
    }
}

</script>

其他回答

有了新的ES6/ES2015特性,你不再需要使用对象来遍历散列。你可以使用地图。Javascript地图保持键的插入顺序,这意味着你可以迭代它们,而不必检查hasOwnProperty,这一直是一个真正的黑客。

迭代一个地图:

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

for (var key of myMap.keys()) {
  console.log(key);
}
// Will show 2 logs; first with "0" and second with "1"

for (var value of myMap.values()) {
  console.log(value);
}
// Will show 2 logs; first with "zero" and second with "one"

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

或使用forEach:

myMap.forEach(function(value, key) {
  console.log(key + " = " + value);
}, myMap)
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

在参数中定义object,避免选择器和下标

有许多语法选择,但这个在闭包的参数中定义了前面的对象,从而消除了迭代器中选择器或下标的需要。K是键,v是值,I是索引。

const obj = {
    kiwi: true,
    mango: false,
    pineapple: 500
};

Object.entries(obj).forEach(([k, v], i) => {
    console.log(k, v, i);
});

// kiwi true 0
// mango false 1
// pineapple 500 2
var Dictionary = {
  If: {
    you: {
      can: '',
      make: ''
    },
    sense: ''
  },
  of: {
    the: {
      sentence: {
        it: '',
        worked: ''
      }
    }
  }
};

function Iterate(obj) {
  for (prop in obj) {
    if (obj.hasOwnProperty(prop) && isNaN(prop)) {
      console.log(prop + ': ' + obj[prop]);
      Iterate(obj[prop]);
    }
  }
}
Iterate(Dictionary);

如果你想一次迭代整个对象,你可以使用for in循环:

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

但如果你想把物体分成几部分实际上你做不到。不能保证对象中的属性按任何指定的顺序排列。因此,我可以想到两种解决方案。

首先是“删除”已经读取的属性:

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

我能想到的另一个解决方案是使用数组的数组而不是对象:

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

然后,标准for循环将工作。

如果在迭代时需要键和值,可以使用for…使用Object.entries循环。

const myObj = {a: 1, b: 2}

for (let [key, value] of Object.entries(myObj)) {
    console.log(`key=${key} value=${value}`)
}

// output: 
// key=a value=1
// key=b value=2