Javascript:按数字索引而不是键值循环对象

时间:2017-12-08 19:21:24

标签: javascript loops object nested

使用for(key in object)循环访问对象很简单,我想通过索引(如数组)而不是其值来访问对象。

我有一个“星期几”的对象组成:

days: { sunday: "N", monday: "Y", tuesday: "N", wednesday: "Y", 
thursday: "N", friday: "Y", saturday: "N" }

我想使用循环遍历一周七天(0-6)的for循环,并检查当天对象是“Y”还是“N”(检查“天”对象为键0(星期日),1(星期一),2,3等等的值。

for (var i = 0; i < 7; i++) { }

我的问题可以用一堆if语句if i == 0 { //check sunday } else if i == 1 { //check monday }解决,或者将我的对象操作到多个数组并从那里开始,但这些都不是很优雅。有没有办法循环遍历days对象并通过键访问每个值(0表示第一个,1表示第二个,等等)?

2 个答案:

答案 0 :(得分:1)

以一致的顺序迭代对象的属性, 你别无选择,只能使用属性名称数组, 例如:

var daysList = [ 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ];

然后你可以迭代名字数组:

for (let i = 0; i < daysList.length; i++) {
    let day = daysList[i];
    // do what you need with days[day]
}

答案 1 :(得分:1)

您可以使用Map - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

const days = { sunday: "N", monday: "Y", tuesday: "N", wednesday: "Y", 
thursday: "N", friday: "Y", saturday: "N" }

const map = new Map(Object.entries(days));
var mapIter = map.entries();

x = 0;
while(x < Object.keys(days).length) {
  let next = mapIter.next().value
  if(next[1] == 'Y') {
    console.log(next[0] + " is Y");
  }
  else if(next[1] == 'N') {
    console.log(next[0] + " is N");
  }
  x++;
}