Javascript在foreach循环中更改变量名称

时间:2018-10-13 10:19:40

标签: javascript

我希望在foreach循环中从对象更改变量名

const Foo = () => import('./Foo.vue')

3 个答案:

答案 0 :(得分:0)

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

days.forEach(function(day){
  console.log(agency.openingHours[day].opening)

})

您没有更改变量名称,并且也没有更改。您遍历openingHours对象的键。这样会更正确

答案 1 :(得分:0)

您可以使用days.map()代替days.forEach,因为map()返回一个新数组。

请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

答案 2 :(得分:0)

agency.openingHours[day].opening-与bracket notationagency.openingHours['Monday'].opening)访问对象属性相同,只是不引用变量。

var days = ['monday','tuesday', 'wednesday'];

const agency = {
  openingHours: {
    monday: { opening: '0900' },
    tuesday: { opening: '0500' },
    wednesday: { opening: '1000' }
  }
}

days.forEach(function(day, index) {
  console.log(agency.openingHours[day].opening);
});