Table of Contents
Basic types and reference types in js
in js Basic types and reference types
Home Web Front-end JS Tutorial Basic types and reference types in js

Basic types and reference types in js

Apr 10, 2018 pm 02:10 PM
javascript Quote type

The content shared with you in this article is about the basic types and reference types in js. It has certain reference value. Friends in need can refer to it


Basic types and reference types in js


Reprinted from https://blog.csdn.net/shuidinaozhongyan/article/details/72520842
Basic type: Number, String,Boolean,Null,undefined.

Reference types: Object, Array, Date, RegExp, Function

The difference between null and undefined.

Reference: http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html

1. Similarity

1. In JavaScript, assigning a variable to undefined or null, to be honest, there is almost no difference.

var a=null;  
var b=undefined;
Copy after login
Copy after login

2. Undefined and null will be automatically converted to false in the if statement, and the equality operator will even directly report that they are equal.

if (!undefined) 
    console.log('undefined is false');// undefined is falseif (!null) 
    console.log(&#39;null is false&#39;);// null is falseundefined == null// true<span style="font-family:Georgia, serif;color:#111111;"><span style="font-size:16px;letter-spacing:-.12px;word-spacing:2.4px;background-color:rgb(245,245,213);"><strong>
</strong></span></span>
Copy after login
Copy after login

The above code illustrates how similar the behaviors of the two are!

Since the meanings and usage of undefined and null are similar, why do we need to set two such values ​​at the same time? Doesn't this increase the complexity of JavaScript for no reason and trouble beginners? The Dart language, a replacement for the JavaScript language developed by Google, clearly stipulates that there is only null and no undefined!

2.

Recently, when I was reading the new book "Speaking JavaScript", I accidentally discovered the answer to this question!

It turns out that this is related to the history of JavaScript. When JavaScript was born in 1995, initially like Java, only null was set as the value representing "nothing".

According to the tradition of C language, null is designed to be automatically converted to 0.

Number(null)// 05 + null// 5
Copy after login
Copy after login

However, JavaScript designer Brendan Eich feels that this is not enough, for two reasons.

First of all, null is treated as an object just like in Java. However, JavaScript data types are divided into two categories: primitive types (primitive) and composite types (complex). Brendan Eich feels that the value representing "none" is best not an object.

Secondly, the initial version of JavaScript did not include an error handling mechanism. When a data type mismatch occurs, the type is often automatically converted or fails silently. Brendan Eich feels that if null is automatically converted to 0, it will be difficult to find errors.

Therefore, Brendan Eich designed another undefined.

3. Initial design
The initial version of JavaScript is distinguished as follows: null is an object that represents "none" and is 0 when converted to a numerical value; undefined is a representation of " The original value of "None" is NaN when converted to a numerical value.

Number(undefined)// NaN5 + undefined// NaN
Copy after login
Copy after login

4. Current usage
However, the above distinction quickly proved to be unfeasible in practice. Currently, null and undefined are basically synonymous, with only some subtle differences.

null means "no object", that is, there should be no value there. Typical usage is:

(1) As a parameter of a function, it means that the parameter of the function is not an object.

(2) As the end point of the object prototype chain.

Object.getPrototypeOf(Object.prototype)
// null

undefined means "missing value", that is, there should be a value here, but it has not been defined yet. Typical usage is:

(1) When the variable is declared but not assigned a value, it is equal to undefined.

(2) When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined.

(3) The object has no assigned attribute, and the value of this attribute is undefined.

(4) When the function does not return a value, it returns undefined by default.

var i;
i // undefinedfunction f(x){console.log(x)}
f() // undefinedvar  o = new Object();
o.p // undefinedvar x = f();
x // undefined
Copy after login
Copy after login

Is Object a reference type?

 Object是一个基础类型,其他所有类型都从Object继承了基本行为。比如原型链中它的原型为null。
Copy after login
Copy after login

What is the difference between reference types and basic types? Which one is on the heap and which one is on the stack?

1. Basic type variables are stored in the stack area (the stack area refers to the stack memory in the memory)

Then its storage structure is as follows:

Basic types and reference types in js

The stack area includes variable identifiers and variable values.

2.

Javascript is different from other languages. It does not allow direct access to the location in the memory, which means that the memory space of the object cannot be directly manipulated. Then we operate What? In fact, it is a reference to the operating object,
so the value of the reference type is accessed by reference.
To be precise, the storage of reference types requires the stack area and the heap area of ​​the memory (the heap area refers to the heap memory in the memory). The stack area memory stores the variable identifier and the pointer to the object in the heap memory.
It can also be said to be the address of the object in the heap memory.
If there are the following objects:

var person1 = {name:&#39;jozo&#39;};var person2 = {name:&#39;xiaom&#39;};var person3 = {name:&#39;xiaoq&#39;};
Copy after login
Copy after login

The situation of these three objects saved in memory is as follows:

Basic types and reference types in js

in js Basic types and reference types

Reprinted from https://blog.csdn.net/shuidinaozhongyan/article/details/72520842
Basic types: Number, String, Boolean, Null, undefined.

Reference types: Object, Array, Date, RegExp, Function

The difference between null and undefined.

Reference: http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html

1. Similarity

1.在JavaScript中,将一个变量赋值为undefined或null,老实说,几乎没区别。

var a=null;  
var b=undefined;
Copy after login
Copy after login

2.undefined和null在if语句中,都会被自动转为false,相等运算符甚至直接报告两者相等。

if (!undefined) 
    console.log(&#39;undefined is false&#39;);// undefined is falseif (!null) 
    console.log(&#39;null is false&#39;);// null is falseundefined == null// true<span style="font-family:Georgia, serif;color:#111111;"><span style="font-size:16px;letter-spacing:-.12px;word-spacing:2.4px;background-color:rgb(245,245,213);"><strong>
</strong></span></span>
Copy after login
Copy after login

上面代码说明,两者的行为是何等相似!

既然undefined和null的含义与用法都差不多,为什么要同时设置两个这样的值,这不是无端增加JavaScript的复杂度,令初学者困扰吗?Google公司开发的JavaScript语言的替代品Dart语言,就明确规定只有null,没有undefined!

二、

最近,我在读新书《Speaking JavaScript》时,意外发现了这个问题的答案!

原来,这与JavaScript的历史有关。1995年JavaScript诞生时,最初像Java一样,只设置了null作为表示”无”的值。

根据C语言的传统,null被设计成可以自动转为0。

Number(null)// 05 + null// 5
Copy after login
Copy after login

但是,JavaScript的设计者Brendan Eich,觉得这样做还不够,有两个原因。

首先,null像在Java里一样,被当成一个对象。但是,JavaScript的数据类型分成原始类型(primitive)和合成类型(complex)两大类,Brendan Eich觉得表示”无”的值最好不是对象。

其次,JavaScript的最初版本没有包括错误处理机制,发生数据类型不匹配时,往往是自动转换类型或者默默地失败。Brendan Eich觉得,如果null自动转为0,很不容易发现错误。

因此,Brendan Eich又设计了一个undefined。

三、最初设计
JavaScript的最初版本是这样区分的:null是一个表示”无”的对象,转为数值时为0;undefined是一个表示”无”的原始值,转为数值时为NaN。

Number(undefined)// NaN5 + undefined// NaN
Copy after login
Copy after login

四、目前的用法
但是,上面这样的区分,在实践中很快就被证明不可行。目前,null和undefined基本是同义的,只有一些细微的差别。

null表示”没有对象”,即该处不应该有值。典型用法是:

(1) 作为函数的参数,表示该函数的参数不是对象。

(2) 作为对象原型链的终点。

Object.getPrototypeOf(Object.prototype)
// null

undefined表示”缺少值”,就是此处应该有一个值,但是还没有定义。典型用法是:

(1)变量被声明了,但没有赋值时,就等于undefined。

(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。

(3)对象没有赋值的属性,该属性的值为undefined。

(4)函数没有返回值时,默认返回undefined。

var i;
i // undefinedfunction f(x){console.log(x)}
f() // undefinedvar  o = new Object();
o.p // undefinedvar x = f();
x // undefined
Copy after login
Copy after login

Object是引用类型嘛?

 Object是一个基础类型,其他所有类型都从Object继承了基本行为。比如原型链中它的原型为null。
Copy after login
Copy after login

引用类型和基本类型有什么区别?哪个是存在堆哪一个是存在栈上面的?

1.基本类型的变量是存放在栈区的(栈区指内存里的栈内存)

那么它的存储结构如下图:

Basic types and reference types in js

栈区包括了 变量的标识符和变量的值。

2.

javascript和其他语言不同,其不允许直接访问内存中的位置,也就是说不能直接操作对象的内存空间,那我们操作啥呢? 实际上,是操作对象的引用,
所以引用类型的值是按引用访问的。
准确地说,引用类型的存储需要内存的栈区和堆区(堆区是指内存里的堆内存)共同完成,栈区内存保存变量标识符和指向堆内存中该对象的指针,
也可以说是该对象在堆内存的地址。
假如有以下几个对象:

var person1 = {name:&#39;jozo&#39;};var person2 = {name:&#39;xiaom&#39;};var person3 = {name:&#39;xiaoq&#39;};
Copy after login
Copy after login

则这三个对象的在内存中保存的情况如下图:

Basic types and reference types in js

相关推荐:

JS引用类型的介绍

The above is the detailed content of Basic types and reference types in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to create a video matrix account? What types of matrix accounts do it have? How to create a video matrix account? What types of matrix accounts do it have? Mar 21, 2024 pm 04:57 PM

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

How to use C++ reference and pointer parameter passing? How to use C++ reference and pointer parameter passing? Apr 12, 2024 pm 10:21 PM

References and pointers in C++ are both methods of passing function parameters, but there are differences. A reference is an alias for a variable. Modifying the reference will modify the original variable, while the pointer stores the address of the variable. Modifying the pointer value will not modify the original variable. When choosing to use a reference or a pointer, you need to consider factors such as whether the original variable needs to be modified, whether a null value needs to be passed, and performance considerations.

What is the type of return value of Golang function? What is the type of return value of Golang function? Apr 13, 2024 pm 05:42 PM

Go functions can return multiple values ​​of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of ​​a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.

See all articles