为null javascript对象成员分配新值

时间:2014-09-24 22:07:39

标签: javascript json

我在找出如何在我的对象中找到空值并用0替换它们时遇到了问题。我能够在一个点上访问正确的成员,但是一旦它离开循环,他们就不再被赋予0.我在js中处理对象时相当新,所以我很丢失。任何帮助将不胜感激。

var data = { 
    0 : {
         Day1: {
               Hours: 6,
               Minutes: null
         },
         Day2: {
               Minutes: 45
         },
         Day3: {
               Hours: 8,
               Minutes: 15
         },
    1 : {
         Day1: {
               Hours: 6,
               Minutes: 20
         },
         Day2: {
               Hours: 45
               Minutes: null
         },
         Day3: {
               Hours: 8,
               Minutes: 15
         }
};


for (var item in data) {
    for (var item2 in item) {
         item[item2].Hours = item[item2].Hours || 0;
         item[item2].Minutes = item[item2].Minutes || 0;
    }
}

//Ignore this line. Just assigning onject to angular scope when finished
$scope.timeInfo = data;

1 个答案:

答案 0 :(得分:1)

@Ian是正确的,他说在for (variable in object)循环中变量引用对象键属性名称。因此,在您的情况下,实现目标的一种方法如下:

(注意:我继续在data对象中添加了一些缺失的大括号。)

var data = { 
    0 : {
         Day1: {
               Hours: 6,
               Minutes: null
         },
         Day2: {
               Minutes: 45
         },
         Day3: {
               Hours: 8,
               Minutes: 15
         }
    },
    1 : {
         Day1: {
               Hours: 6,
               Minutes: 20
         },
         Day2: {
               Hours: 45,
               Minutes: null
         },
         Day3: {
               Hours: 8,
               Minutes: 15
         }
    }
};


for (var item in data) {
    for (var item2 in data[item]) {
         data[item][item2].Hours = data[item][item2].Hours || 0;
         data[item][item2].Minutes = data[item][item2].Minutes || 0;
    }
}