通过JavaScript数组循环 [英] Loop through array in JavaScript

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

问题描述

在Java中,你可以使用为()循环来遍历对象,像这样的数组:

In Java you can use a for() loop to go through objects in an array like so:

String[] myStringArray = {"Hello","World"};
for(String s : myStringArray)
{
    //Do something
}

您可以做同样的在JavaScript中?

Can you do the same in JavaScript?

推荐答案

使用顺序循环:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    alert(myStringArray[i]);
    //Do something
}

@拉链codeMAN建议使用的为中... 语句,但对于迭代数组换的应避免,这种说法是为了枚举对象属性。

@zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.

它不应该被用于阵列状物体,因为:

It shouldn't be used for array-like objects because:


  • 迭代的顺序是不能保证,则数组索引可能不会按数字顺序参观。

  • 继承属性,还列举了。

第二点是,它可以给你很多的问题,例如,如果延长 Array.prototype 对象包括一个方法那里,属性将可还列举了。

The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.

例如:

Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
  alert(array[i]);
}

以上code会提醒,A,B,C和富!

The above code will alert, "a", "b", "c" and "foo!".

如果你使用一些库,在很大程度上依赖于原生的原型augmention(如MooTools的为例)这是特别有问题。

That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).

换的语句就像我之前说的是那里的枚举的对象属性,例如:

The for-in statement as I said before is there to enumerate object properties, for example:

var obj = {
  "a": 1,
  "b": 2,
  "c": 3
};

for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) { 
  // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
    alert("prop: " + prop + " value: " + obj[prop])
  }
}

在上面的例子中的hasOwnProperty 方法允许你只枚举的自己的属性的,就是这样,只有该对象实际拥有的属性,没有继承的属性。

In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.

我建议你阅读以下文章:

I would recommend you to read the following article:

  • Enumeration VS Iteration

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

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