javascript foreach如何与多维数组一起使用? [英] How javascript foreach works with multi-dimensional arrays?

查看:81
本文介绍了javascript foreach如何与多维数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩一些javascript并且发现(至少对我来说)通过foreach循环处理多维数组时的奇怪行为。所以我有这段代码:

I was playing a bit with javascript and found out (at least for me) strange behaviour when dealing with multi-dimensional arrays via a foreach loop. So I have this piece of code:

<script type="text/javascript">
  var arr = [['a', 'b'], ['c','d']];

  var first='';

  for (var singleArray in arr) {
    first += ' ' + singleArray[0] + ' ' + singleArray[1];
  }

  var second = '';
  for (var i=0;i<arr.length; i++) {
    second += ' ' + arr[i][0] + ' ' + arr[i][1];
  }

  console.log('First: ', first);
  console.log('Second: ', second);
</script>

输出为:

First: 0 undefined 1 undefined
Second: a b c d

I我希望第一和第二将是相同的。你能解释一下我错过了什么吗?

I would expect the first and second will be the same. Can you please explain me what I am missing?

注意:请不要建议通过jQuery或其他方式迭代数组。我没有编码麻烦,我只是对这种特殊情况感到好奇。谢谢!

Note: please do not advice to iterate over the array via jQuery or somehow else. I don't have coding troubles, I am just curious about this particular situation. Thanks!

推荐答案

埃里克·米克尔森指出了一些好点,但总结一下。

There were some good point from Erick Mickelsen pointed out but so sum it up.


  1. for(... in ...)循环迭代对象属性

  2. array 是Javascript中的一个对象,因此您可以使用它迭代一个数组。但它会慢一些,一般不推荐(参见为什么会这样

  3. 它迭代属性而不是值的事实意味着它返回索引而不是数组值(当你有关联数组时这可能很方便)

  4. 问题中的示例可以通过解决(... in ...) loop

  1. for (... in ...) loop iterates over object properties
  2. array IS an object in Javascript so you may iterate over an array with it. But it will be slower and it is generaly not recommended (see why is that)
  3. The fact that it iterates over properties rather than values means, that it returns indexes rather than array values (this may be handy when you have associative arrays)
  4. The example in the question may be solved with for (... in ...) loop

如下:

var third = '';
for (var arrayIndex in arr) {
  third += ' ' + arr[arrayIndex][0] + ' ' + arr[arrayIndex][1];
}

在关联数组示例中,为(.. 。在...)循环将很方便:

In the associative array example the for (... in ...) loop will be handy:

var person = [];
person["id"] = 1;
person["born"] = 2009;
person["favourite_meal"] = "chicken"; 

var fourth = '';
for (var arrayIndex in person) {
  fourth += ' ' + person[arrayIndex];
}

这篇关于javascript foreach如何与多维数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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