“空"和“未定义"之间的区别在于:用Javascript? [英] Difference between "empty' and "undefined" in Javascript?
问题描述
根据ECMAScript,有null
和undefined
个数据类型彼此分开.
但是最近我看到了一个叫做empty
的东西.让我们首先重新生成它(我将从基础知识开始):
According to ECMAScript there are null
and undefined
datatypes apart from others.
But recently I got to see something called empty
. Let's regenerate it first (I'll go from basic):
let a = new Array()
//返回[]
length = 0
let a = new Array()
//Returns []
length=0
let b = new Array(3)
//返回[empty*3]
length = 3
let b = new Array(3)
//Returns [empty*3]
length=3
let c = new Array(3).fill()
//返回[undefined,undefined,undefined]
length = 3
let c = new Array(3).fill()
//Return [undefined,undefined,undefined]
length=3
现在,什么? 看到所有定义的元素都是未定义的,应该是
Now, what? See all the elements defined are undefined, which they should be
-
a[0]=undefined
-
b[0]=undefined
-
c[0]=undefined
a[0]=undefined
b[0]=undefined
c[0]=undefined
主要内容:
如果假设将元素添加到c
中的位置5,即a[5]=4
那么c
将是[undefined,undefined,undefined,empty,4]
Main thing:
If suppose add an element into c
at position 5 i.e a[5]=4
then c
will be [undefined,undefined,undefined,empty,4]
这之间的空东西是什么?如果一切相同,开始b
和c
的初始化有什么区别(我说的是[empty*3]
& [undefined,undefined,undefined]
).
What is this empty thing in between? And if everything is same what is the difference in starting initialization of b
and c
( I'm talking about [empty*3]
& [undefined,undefined,undefined]
).
The Answer suggested [here]: What's the difference between empty items in a JavaScrip array and undefined? Doesn't explains the properly about what exactly it is. Yes it can't be undefined
as undefined
is a value but what about null
and if not null
why empty is not a data-type?
推荐答案
数组是对象.那意味着你的数组
Arrays are objects. That means that your array
[undefined,undefined,undefined,empty,4]
可以写成这样的对象:
{
0: undefined,
1: undefined,
2: undefined,
// 3 doesnt exist at all
4: 4,
length: 5,
}
因此,undefined
实际上是一个存在的插槽并保存一个值,而3
甚至不是键值对.由于访问不存在的密钥会导致undefined
的存在,因此与现实世界没有任何区别:
So undefined
is actually a slot that exists and holds a value while 3
is not even a key-value pair. As accessing a non existing key results in undefined
there is no real world difference:
array[2] // undefined
array[3] // undefined
但是使用map
遍历数组时,其他数组将跳过空数组,因此在迭代之前应使用.fill
.
But iterating over an array with map
and others will skip empty ones, so then you should use .fill
before iterating.
检测差异的唯一方法是检查密钥是否存在:
The only way to detect a difference is to check if the key exists:
2 in array // true
3 in array // false
要将empty
转换为undefined
,可以设置键:
To turn empty
to undefined
you could set the key:
array[3] = undefined;
并将undefined
转换为empty
,您必须删除密钥:
and to turn undefined
into empty
you have to remove the key:
delete array[3]
但是很少有关系.
这篇关于“空"和“未定义"之间的区别在于:用Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!