请参阅我的代码:
function foo() {
var h = "start";
$.each(some_array_of_objects, function() {
var name = 'middle';
h += name;
});
h += "end";
alert(h);
}
我希望在我的警报中看到累积的字符串,但是我得到了很多 [object Object] 字符串的字符串。是否有可能以上述方式积累 h 变量而不使用全局变量?
答案 0 :(得分: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"