在Javascript中循环遍历数组的元素 [英] Looping through elements of an array in Javascript

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

问题描述

我在Javascript中有一个数组:

I have an array in Javascript:

var array = new array();
array[0] = "apples";
array[1] = "oranges";
array[2] = "pears";

在PHP中,对于给定的数组,我可以使用以下方法遍历数组,并打破键和值:

In PHP, with a given array, I can use the following to loop through an array, and break up the keys and values:

foreach ($array as $key => $value) {
    echo("Key is $key and Value is $value");
}

如何在Javascript中执行此操作?我知道:

How can I do this in Javascript? I'm aware of:

for (x in array){
    // Do something with x.
}

但我发现没有什么可以复制php风格的foreach。是否有可能简洁地在Javascript中实现类似的东西? (我也使用jQuery,如果可以在jQuery中完成某些事情)。

But I've found nothing that will replicate the php style foreach. Is it possible to concisely achieve something similar in Javascript? (I'm also using jQuery, if something can be done in jQuery).

推荐答案

首先,

var array=[];

比使用new更好。

其次,在这种情况下你的键是数字的,所以你只需:

Second, your keys are numeric in this case, so you just do:

for (i=0;i<array.length;i++) {
  console.log("Key is "+i+" and Value is "+array[i]);
}

如果您想拥有非数字键,请使用JavaScript对象而不是数组。使用字符串而不是数字作为数组索引是有效的,但JavaScript对此没有太多支持。

If you want to have keys that aren't numeric, use a JavaScript object instead of an array. It's valid to use strings instead of numbers as array indexes, but JavaScript doesn't have much support for that.

I使用console.log,因为我假设您不希望弹出一堆警报。 console.log可以替换为用于记录信息的任何内容。您可以使用alert()或将文本写入div。

I use "console.log" because I assume you don't want a bunch of alerts popping up. console.log could be replaced with whatever you use to log info. You could use alert() or write text into a div instead.

这篇关于在Javascript中循环遍历数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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