2012-11-30 54 views
0

请看看我的代码:积累变量在不同的范围

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

我希望看到我的警戒累积字符串,但不是这个我串了很多的翻译:字符串。是否有可能以上述方式积累h变量而不使用全局变量?

+1

这是最有可能的,因为'$(本)[0] [ '名']'是一个数组。你可以发布'some_array_of_object'变量的值。 –

+0

请将代码发布到'this'引用的对象。 –

+1

你没有使用“全局变量”。 'h'只能在'function foo()'的范围内使用。 现在,你能告诉我们'some_array_of_objects'的内容吗? – Cerbrus

回答

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" 
+0

好的,谢谢,但是我的代码有什么问题?变量作用域是否存在一些限制? –

+0

我不太清楚你这个问题的含义。 – Cerbrus