关联数组的for / in循环问题 [英] Problem with for/in loop over associative array

查看:132
本文介绍了关联数组的for / in循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我遇到了循环关联数组的问题。所有

与以下代码完美配合:


for(var menuItem in this.menuItems){

doSomething();

}


其中this.menuItems是一个关联数组。当

我将以下函数添加到Array原型时发生了问题:


Array.prototype.print_r = function(){

print_the_array_code();

}


添加此方法后,for / in循环将print_r作为元素
$ b $好吧。所以除了我实际想要从我的阵列中得到的项目之外,我还要去打印__,这显然是我不想要的。有没有人有一个

建议如何处理这个...?


提前致谢,

Yereth Jansen

推荐答案

>我在循环关联数组时遇到了问题。所有
> I encountered a problem with looping through an associative array. All
都完美地使用了以下代码:

for(var menuItem in this.menuItems){
doSomething();
}
其中this.menuItems是一个关联数组。当我将以下函数添加到Array原型时发生了问题:

Array.prototype.print_r = function(){
print_the_array_code();
}

添加此方法后,for / in循环将print_r作为元素
。所以除了我想从我的阵列中获得的项目之外,我还要去print_r,这显然我不想要。有没有人有一个
建议怎么做...?
worked perfectly with the following code:

for (var menuItem in this.menuItems) {
doSomething();
}

where this.menuItems is an associative array. The problem occurred when
I added the following function to the Array prototype:

Array.prototype.print_r = function() {
print_the_array_code();
}

After adding this method, the for/in loop took print_r as an element as
well. So besides the items I actually wanted to get from my array, I
also go print_r, which obviously I don''t want. Does anyone have a
suggestion what to do with this..?




你的应该是


for (var i; i< this.menuItems.length; i + = 1){

http://www.crockford.com/javascript/survey.html


Douglas Crockford写道:
Douglas Crockford wrote:
你的应该是

(var i; i< this.menuItems.length; i + = 1){

http://www.crockford.com/javascript/survey.html




那不行。我在哈希中使用关联数组。一个

关联数组没有数字索引也没有像我想要的那样设置

属性.length。 "。长度"在所有情况下都为0.



That won''t work. I am using an associative array as in a hash. An
associative array does not have a numerical index nor does it have the
property .length set like I want it. ".length" is 0 in all cases.


>>你的for应该是
>> Your for should be

for(var i; i< this.menuItems.length; i + = 1){

http://www.crockford.com/javascript/survey.html



那不行。我在哈希中使用关联数组。
关联数组没有数字索引也没有像我想要的那样具有
属性.length设置。 "。长度"在所有情况下都是0。



That won''t work. I am using an associative array as in a hash. An
associative array does not have a numerical index nor does it have the
property .length set like I want it. ".length" is 0 in all cases.




当你不需要.length时不要使用Array。你应该使用

对象。最好不要使用术语关联阵列。在JavaScript中使用
时,因为它会让你感到困惑。


对你提取的值使用typeof运算符,并跳过那些

是''功能''。

http://www.crockford.com/javascript/survey.html


这篇关于关联数组的for / in循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆