JavaScript 数组中的空项和未定义之间有什么区别? [英] What's the difference between empty items in a JavaScript array and undefined?

查看:35
本文介绍了JavaScript 数组中的空项和未定义之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 JavaScript 代码(在节点 REPL 中):

Consider the following JavaScript code (in a node REPL):

> let a = new Array(10)
undefined
> a
[ <10 empty items> ]
> a.map(e => 1)
[ <10 empty items> ]
> let b = new Array(10).fill(undefined)
undefined
> b
[ undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined ]
> b.map(e => 1)
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
> 

当我创建一个空数组时,我会得到空项目",它们的行为似乎与 undefined 不同.有人能解释一下有什么区别吗?

When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?

推荐答案

当我创建一个空数组时,我会得到空项目",这似乎是行为与 undefined 不同.谁能解释一下区别?

When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?

那是因为 Array(10) 没有填充数组.但它只是将 length 属性设置为 10 .所以,使用 Array 构造函数创建的数组只是一个具有长度属性的对象,但是未填充任何项目.

That's because Array(10) doesn't populate the array. But it just set the length property to 10 .So, the array created using Array constructor is simply an object with a length property, but with no items populated.

这篇关于JavaScript 数组中的空项和未定义之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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