0

请看我的代码:

function foo() {
    var h = "start";
    $.each(some_array_of_objects, function() {
        var name = 'middle';        
        h += name;
    });
    h += "end";
    alert(h);
}

我希望在我的警报中看到累积的字符串,但不是这个,而是包含很多[object Object]字符串的字符串。是否可以在不使用全局变量的情况下以上述方式累积h变量?

4

1 回答 1

0

无需使用 jQuery 循环遍历数组/对象,只需for对数组使用循环,for-in对对象使用循环。这将适用于您的情况:

//Assuming the input array is something like this:
some_array_of_objects = [[{name:'ABC'}],[{name:'I am a name'}],[{name:'Look at me!'}],[{name:'foo'}],[{name:'bar'}]]

function foo() {
    var h = "start";
    // Loop through the array.
    for(var i = 0; i < some_array_of_objects.length; i++){
        var name = some_array_of_objects[i][0].name;        
        h += name;
    }
    h += "end";
    alert(h);
}
foo(); //Returns: "startABCI am a nameLook at me!foobarend"
于 2012-11-30T10:07:22.960 回答