对象未定义 - Javascript

时间:2017-01-04 06:58:12

标签: javascript angularjs

我有一个列表,我需要根据某些计算获取值。请查看以下代码以获得更多理解。

 $scope.allcolors = [
                            { id:1, color:'#67b05c' },
                            { id:2, color:'#7dc47a'},
                            { id:3, color:'#b4cf8a' },
                            { id:4, color:'#c7c354'},
                            { id:5, color:'#e5e154' },
                            { id:6, color:'#e5e154'},
                            { id:7, color:'#eb9d54' },
                            { id:8, color:'#db8a42'},
                            { id:9, color:'#cf9373' },
                            { id:10, color:'#db755e'}
                            ];
    if(r_header.severity){
                console.log("sev", r_header.severity);
                for (var i in $scope.allcolors) {
                    if ($scope.allcolors[i].id == r_header.severity) {
                        console.log("color", object.values($scope.allcolors[i]))}
                }}

r_header.severity是一个整数变量,其值为1到10.根据此值,我需要在列表中指定颜色。上面的代码标记了Object未定义的错误。我检查了类似的引用,但似乎没有什么适合我的情况。

3 个答案:

答案 0 :(得分:1)

更改for循环:

for (var i=0; i<$scope.allcolors.length; i++) {
    if ($scope.allcolors[i].id == r_header.severity) {
        console.log("color", $scope.allcolors[i].color)}
    }
}

答案 1 :(得分:0)

在for循环中,每次迭代都会返回i中数组的对象,意味着&#39; i =对象(&#34; id&#34;,&#34;颜色&#34;)&#39 ;

&#13;
&#13;
 $scope.allcolors = [
                            { id:1, color:'#67b05c' },
                            { id:2, color:'#7dc47a'},
                            { id:3, color:'#b4cf8a' },
                            { id:4, color:'#c7c354'},
                            { id:5, color:'#e5e154' },
                            { id:6, color:'#e5e154'},
                            { id:7, color:'#eb9d54' },
                            { id:8, color:'#db8a42'},
                            { id:9, color:'#cf9373' },
                            { id:10, color:'#db755e'}
                            ];
    if(r_header.severity){
                console.log("sev", r_header.severity);
                for (var i in $scope.allcolors) {
                    if (i.id == r_header.severity) {
                        console.log("color", i.color))}
                }}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果要查看所有对象

,请尝试此操作

console.log("color", JSON.stringify($scope.allcolors[i]))}

for (var i=0; i<$scope.allcolors.length; i++) {

而不是

console.log("color", object.values($scope.allcolors[i]))}

for (var i in $scope.allcolors) {