javascript - for(i in array) 和 for(var i=0;i<array.length;i++) 的区别

标签 javascript jquery for-loop

<分区>

对于所有 javascript/jquery 的人来说,这将是一个非常简单的问题。

过去 2 年我一直在编写 javascript,今天我遇到了一个奇怪的问题。

我正在从我的 C# Webmethod 中获取一个 JSONarray 并通过 jQuery.ajax() 调用它

当我做的时候

for (i in JSONRaw) {
    Index = Index + 1;
    $('#bottomGridDashboard').append('<tr> <td>' + Index + '</td> <td>' + JSONRaw[i].DisplayName + '</td> <td>' + JSONRaw[i].SpeedInKPH + '</td> <td><img src="' + JSONRaw[i].ImageURL + '" height="20px" alt="" /></td> <td>' + JSONRaw[i].DepotID + '</td> <td>' + JSONRaw[i].RouteID + '/' + JSONRaw[i].ScheduleID + '/' + JSONRaw[i].TripID + '</td> <td>' + JSONRaw[i].Direction + '</td> <td>' + JSONRaw[i].LastStop + '</td> <td> ' + JSONRaw[i].ETAMinutes + ' </td> </tr>');
}

附加表添加了两个额外的行,将每个字段都设置为“未定义”。 See this Image

但是,如果我用

替换循环
for (var i = 0; i < JSONRaw.length;i++ ) {
    Index = Index + 1;
    $('#bottomGridDashboard').append('<tr> <td>' + Index + '</td> <td>' + JSONRaw[i].DisplayName + '</td> <td>' + JSONRaw[i].SpeedInKPH + '</td> <td><img src="' + JSONRaw[i].ImageURL + '" height="20px" alt="" /></td> <td>' + JSONRaw[i].DepotID + '</td> <td>' + JSONRaw[i].RouteID + '/' + JSONRaw[i].ScheduleID + '/' + JSONRaw[i].TripID + '</td> <td>' + JSONRaw[i].Direction + '</td> <td>' + JSONRaw[i].LastStop + '</td> <td> ' + JSONRaw[i].ETAMinutes + ' </td> </tr>');
}

未定义的行消失.. See the image

我为我的愚蠢道歉,但我以前从未遇到过任何此类问题。 可能是什么原因??

编辑:

数组非常好。而且里面没有洞。 另一个观察是未定义的属性只出现在我的网格底部。我认为它正在处理两个多于数组长度的额外索引。

EDIT-2

我的 console.log 显示了数组中的以下元素。

http://i.imgur.com/rI5TjdK.jpg

我已经在我的母版页中声明了原型(prototype)。

Array.prototype.inArray = function (comparer) {
    for (var i = 0; i < this.length; i++) {
        if (comparer(this[i])) return true;
    }
    return false;
};


Array.prototype.pushIfNotExist = function (element, comparer) {
    if (!this.inArray(comparer)) {
        this.unshift(element);
    }
};

是否增加数组长度。 ? ?

最佳答案

JavaScript 的 for-in和 C# 的 foreach是完全不同的东西。不要使用 for-in除非您使用适当的保护措施,否则循环遍历数组,这不是它的目的。它遍历对象的可枚举属性,而不是数组索引或条目。

要么使用必要的保护措施,要么使用通用的 for就像你的第二个例子,或者(如果你可以依赖它)使用 Array#forEach .

更多信息 this SO answeron my blog .


另外:确保您声明了 i某处(你似乎不在你的第一个例子中)。如果你不这样做,你就会成为 The Horror of Implicit Globals 的牺牲品。 .


I've declared the prototypes in my Master page.

Array.prototype.inArray = function ...

这就是您不使用 for-in 的原因用于在没有安全措施的情况下遍历数组。再次,请参阅上面的链接。你的for-in loop 将遍历数组索引属性( "0""1" 等等 -- 是的,它们确实是字符串)以及您添加到Array.prototype (inArray 等)。

关于javascript - for(i in array) 和 for(var i=0;i<array.length;i++) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160575/

相关文章:

javascript - 使用 Node.js 在 JSON 文件中写入/添加数据

jquery - 如何将短代码添加到 blogspot?

java - 更改 java 循环中的输入变量

c++ - vector +for+if

javascript - 预加载器不会停止并且不会转换到主页

javascript - 如何迭代数组 - jquery

javascript - 捕获屏幕尺寸并在 HTML/JavaScript 中创建覆盖

php - jquery ajax 应该转到同一页面还是另一个 php 文件?

javascript - 单击按钮时如何移动轮播项目?

arrays - 算法问题 - 在列表中查找一组项目