“空"和“未定义"之间的区别在于:用Javascript? [英] Difference between "empty' and "undefined" in Javascript?

查看:76
本文介绍了“空"和“未定义"之间的区别在于:用Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据ECMAScript,有nullundefined个数据类型彼此分开. 但是最近我看到了一个叫做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]

这之间的空东西是什么?如果一切相同,开始bc的初始化有什么区别(我说的是[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屋!

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