在JavaScript中循环访问数组 [英] Loop through an array in JavaScript
问题描述
来循环循环中的对象,如下所示:
String [] myStringArray = {Hello,World};
for(String s:myStringArray)
{
//做某事
}
你可以在JavaScript中做同样的事情吗?
解决方案 对于循环:
var myStringArray = [Hello,World];
var arrayLength = myStringArray.length;
for(var i = 0; i< arrayLength; i ++){
alert(myStringArray [i]);
//做点什么
}
@zipcodeman建议使用 for ... in
语句,但是为了迭代数组 for-in
应该被避免,那么这个语句的意思是枚举对象属性。
它不应该用于类似数组的对象,因为:
- 不保证迭代顺序,数组顺序不能按数字顺序访问。
- 继承的属性也被枚举。 b
$ b $ p
$ b 第二点是它可以给你很多问题,例如,如果扩展 Array.prototype
pre> Array.prototype.foo =foo!;
var array = ['a','b','c'];
(var i在数组中){
alert(array [i]);
上面的代码会提示a,b,c 和foo!。
如果使用一些依赖本机原型增强的库(例如MooTools),那么这尤其是个问题。
如前所述, for-in
语句用于枚举对象属性,例如:
var obj = {
a:1,
b:2,
c:3
};
(obj){
if(obj.hasOwnProperty(prop)){
// if(Object.prototype.hasOwnProperty.call(obj,prop ))...
alert(prop:+ prop +value:+ obj [prop])
}
}
在上面的例子中, hasOwnProperty
方法只允许枚举自己的属性,就是这样,只有对象的物理属性,没有继承属性。
我建议你阅读下面的文章:
In Java you can use a for
loop to traverse objects in an array as follows:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
// Do something
}
Can you do the same in JavaScript?
解决方案 Use a sequential for
loop:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
alert(myStringArray[i]);
//Do something
}
@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:
- The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.
- Inherited properties are also enumerated.
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.
For example:
Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];
for (var i in array) {
alert(array[i]);
}
The above code will alert, "a", "b", "c" and "foo!".
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])
}
}
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:
这篇关于在JavaScript中循环访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文