在JavaScript中循环遍历一组对象

时间:2014-10-23 05:58:34

标签: javascript for-loop

您好我在循环查找对象数组以找到最高属性值并返回包含该最高属性值的对象时遇到问题。假设我有这个对象数组:

var eachMapping = [ { I: 1 },
                        { w: 1, a: 1, n: 1, t: 1 },
                        { t: 1, h: 1, i: 1, s: 1 },
                        { w: 1, o: 1, r: 1, d: 6 } ];


    var largest = 0;
        for(var i = 0; i < eachMapping.length; i++){
            for(prop in eachMapping){
                if(eachMapping[i][prop] > largest){
                    largest = eachMapping[i][prop]
                    wantedobject = eachMapping[i];
                }
            }
    }

    console.log(wantedobject)

返回undefined。我希望的是这个循环返回{ w: 1, o: 1, r: 1, d: 6 } 通过将其赋值给wantedobject,因为数组中的所有对象都具有属性值,该属性值是其他对象中所有属性值中最高的。谢谢!

2 个答案:

答案 0 :(得分:0)

var eachMapping = [ { I: 1 },
                    { w: 1, a: 1, n: 1, t: 1 },
                    { t: 1, h: 1, i: 1, s: 1 },
                    { w: 1, o: 1, r: 1, d: 6 } ];


var largest = 0, i = 0, prop, wantedobject;
for(; i < eachMapping.length; i++){
    for(prop in eachMapping[i]) {//you've missed [i], like Emil G wrote in his comment
        if(eachMapping[i][prop] > largest){
            largest = eachMapping[i][prop]
            wantedobject = eachMapping[i];
        }
    }
}

console.log(wantedobject)

答案 1 :(得分:0)

一些基本的编码错误 - 可能解释了downvotes:

  • 未初始化wantedobject
  • 未声明循环变量prop
  • 分号的使用不一致
  • 最大错误未使用for(var prop in eachMapping[i])

这有效:

var eachMapping = [ { I: 1 },
                    { w: 1, a: 1, n: 1, t: 1 },
                    { t: 1, h: 1, i: 1, s: 1 },
                    { w: 1, o: 1, r: 1, d: 6 } ];

var wantedobject = null;
var largest = 0;
    for(var i = 0; i < eachMapping.length; i++){
        for(var prop in eachMapping[i]){
            if(eachMapping[i][prop] > largest){
                largest = eachMapping[i][prop];
                wantedobject = eachMapping[i];
            }
        }
}

console.log(wantedobject);