遍历数组中未定义的方法 [英] Ways to iterate over undefined in Arrays

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

问题描述

我最近发现 .map 不会迭代由有孔数组创建的未定义 ,该数组的各个索引已定义,但其中一些未定义:

I recently discovered that .map does not iterate of the undefined created by holed arrays, arrays whose individual indices were defined, but some weren't:

// Holed
var array = [];
array[0] = 1;
array[2] = 3;
array // => [1, undefined, 3];

// Not Holed
var array = [1, undefined, 3];
array // => [1, undefined, 3]; The "same" as Holed

在迭代时,应该以不同方式定义的这两个应该相同的数组以不同的方式进行迭代(请参阅第一个观点)

When it comes to iteration, these two arrays, which should be identical, defined in different ways are iterated upon differently (see first sentance)

这是我的问题,

  1. 有什么方法可以迭代带孔阵列吗?
  2. 我怀疑这些的确切字节实际上是不同的,并且这种奇怪的行为是由于JavaScript如何显示这些未定义的值,而不是未定义的 .我对么?对于这种异常情况,有什么根本的解释吗?
  1. Is there any way to iterate over the holed arrays?
  2. I suspect that the exact bytes of these are actually different, and this strange behavior is due to how JavaScript displays these values which are not defined, not undefined. Am I correct? Is there any underlying explanation for this anomaly?

非常欢迎任何帮助.谢谢!

Any help is very welcome. Thanks!

推荐答案

有什么方法可以迭代带孔数组吗?

Is there any way to iterate over the holed arrays?

多数(全部?)内置的 Array.prototype 函数会跳过稀疏数组中的孔.

Majority (all?) built-in Array.prototype functions skip holes in sparse arrays.

这意味着,如果要获取缺失索引的 undefined 值-您需要先将该数组转换为非稀疏数组.

That means that if you want to get the undefined value for the missing indexes - you need to turn that array into a non-sparse array first.

借助ES2015,您可以使用数组迭代器.最简单的方法是使用数组扩展语法:

With the help of ES2015 you may use array iterators. The shortest way of doing it would be to use array spread syntax:

[...array]

然后您可以对其应用映射操作符 [... array] .map(handler)

Then you may apply a mapping operator to it [...array].map(handler)

我怀疑它们的确切字节实际上是不同的,并且这种奇怪的行为是由于JavaScript如何显示这些未定义或未定义的值.我对么?对于这种异常情况,有什么根本的解释吗?

I suspect that the exact bytes of these are actually different, and this strange behavior is due to how JavaScript displays these values which are not defined, not undefined. Am I correct? Is there any underlying explanation for this anomaly?

您是正确的,它没有显式保存 undefined 值.由于JS中的数组实际上是所谓的内部对象"(或更短的对象,简称对象),因此它们的索引只是这些对象的属性.因此,当您跳过索引时-该属性只是未设置且不存在.

You are correct, it does not hold the undefined values explicitly. As arrays in JS are actually so called "intrinsic objects" (or shorter - just objects), their indexes are simply the properties of those objects. So when you skip an index - that property is simply not set and does not exist.

与访问不存在的对象属性相同:

It is the same as if you access a non existing object property:

var o = {};
o.foo // undefined

这篇关于遍历数组中未定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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