Home Web Front-end JS Tutorial Detailed explanation of JavaScript basic types and reference types_javascript skills

Detailed explanation of JavaScript basic types and reference types_javascript skills

May 16, 2016 pm 03:26 PM
javascript basic type reference type

1. 値の種類
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​JSのデータ型の紹介で基本型のうち参照型について触れましたが、2つの型について説明する前に、まず変数の値の型について理解しておきましょう。 ECMAScriptでは、変数はプリミティブ値と参照値の2種類の値を持つことができます。
(1) 元の値
単純なデータ セグメントはスタックに格納されます。つまり、その値は変数によってアクセスされる場所に直接格納されます。
(2) 参考値
ヒープに格納されているオブジェクト、つまり変数に格納されている値は、オブジェクトが格納されているメモリを指すポインタです。
変数に値を割り当てるとき、ECMAScript インタープリターは、値がプリミティブ型であるか参照型であるかを判断する必要があります。これを実現するには、インタープリタは、値が ECMAScript の基本タイプ、つまり、未定義タイプ、Null タイプ、ブールタイプ、数値タイプ、および文字列タイプのいずれかであるかどうかを判断する必要があります。これらのプリミティブ型は固定量のスペースを占有するため、より小さなメモリ領域、つまりスタックに格納できます。このストレージにより、変数の値をすばやく簡単に検索できるようになります。
多くの言語では、文字列の長さは可変であるため、文字列はプリミティブ型ではなく参照型として扱われます。 ECMAScript はこれを破ります
伝統。
値が参照型の場合、その記憶領域はヒープから割り当てられます。参照値のサイズが変化するため、スタックに置くことができず、変数の検索速度が低下します。代わりに、変数のスタック領域に配置される値は、オブジェクトがヒープ内に格納されるアドレスになります。アドレスのサイズは固定されているため、スタックに格納しても変数のパフォーマンスに悪影響を与えることはありません。以下に示すように:

2. 基本タイプ
ECMAScript には、Unknown 型、Null 型、Boolean 型、Number 型、String 型の 5 つの基本型があります。 ECMA-262 では、用語タイプを値のコレクションとして定義し、各基本タイプに含まれる値の範囲とそのリテラル表現を定義します。
ECMAScript は、値が特定の型の範囲内にあるかどうかを判断する typeof 演算子を提供します。この演算子を使用すると、値がプリミティブ タイプを表すかどうかを判断できます。値がプリミティブ タイプである場合は、それがどのプリミティブ タイプを表すかを判断することもできます。
基本的なデータ型と演算子 typeof は、以前のブログ投稿でよく使用されています。さらに詳しく知りたい場合は、次の記事を参照してください:JavaScript の変数とデータ型の詳細な説明

3. 型変換
すべてのプログラミング言語の最も重要な機能の 1 つは、型変換を実行する機能です。 ECMAScript は、開発者に多数の単純な型変換メソッドを提供します。ほとんどの型には単純な変換用のメソッドがあり、より複雑な変換用のグローバル メソッドがいくつかあります。どちらの場合も、型変換は ECMAScript での簡単な 1 ステップの操作です。
(1) 文字列
に変換します ECMAScript のブール値、数値、文字列プリミティブの興味深い点は、これらが疑似オブジェクトであることです。つまり、実際にはプロパティとメソッドがあることを意味します。
たとえば、文字列の長さを取得するには、次のコードを使用できます:

var sbox = "red"; 
document.write(sbox.length);//输出3 
Copy after login

「red」は文字列の基本的なタイプですが、文字列のサイズを格納するために使用される属性 length を持っています。要約すると、ブール値、数値、文字列の 3 つの主要なプリミティブ タイプはすべて、値を文字列に変換する toString() メソッドを持っています。 「string にも toString() メソッドがあるのですか? これは冗長ではないでしょうか?」と疑問に思われるかもしれませんが、それは事実ですが、ECMAScript では、疑似オブジェクトであろうと実際のオブジェクトであろうと、すべてのオブジェクトが toString() メソッドを持つと定義されています。物体。 String 型は擬似オブジェクトであるため、toString() メソッドが必要です。
1) ブール型の toString() メソッドは単に「true」または「false」を出力し、結果は変数の値によって決まります:

var bage=false; 
document.write(bage.toString());//输出"false" 
Copy after login

2)Number类型的toString()方法比较特殊,它有两种模式,即默认模式和基模式。采用默认模式,toString()方法只是用相应的字符串输出数字值(无论是整数、浮点数还是科学计数法),在默认模式中,无论最初采用什么表示法声明数字,Number 类型的 toString() 方法返回的都是数字的十进制表示。因此,以八进制或十六进制字面量形式声明的数字输出的都是十进制形式的。如下所示:

var iNum1 = 10; 
var iNum2 = 10.0; 
document.write(iNum1.toString());//输出 "10" 
document.write(iNum2.toString());//输出 "10" 
Copy after login

采用Number类型的 toString()方法的基模式,可以用不同的基输出数字,例如二进制的基是2,八进制的基是8,十六进制的基是16。
基只是要转换成的基数的另一种加法而已,它是 toString() 方法的参数:

var iNum = 10; 
document.write(iNum.toString(2));//输出 "1010" 
document.write(iNum.toString(8));//输出 "12" 
document.write(iNum.toString(16));//输出 "a" 
Copy after login

(2)转换成数字
ECMAScript提供了两种把非数字的原始值转换成数字的方法,即parseInt()和parseFloat()。前者把值转换成整数,后者把值转换成浮点数。只有对String类型调用这些方法,它们才能正确运行;对其他类型返回的都是NaN。
1)parseInt()
在判断字符串是否是数字值前,parseInt()和 parseFloat()都会仔细分析该字符串。parseInt()方法首先查看位置0处的字符,判断它是否是个有效数字;如果不是,该方法将返回NaN,不再继续执行其他操作。但如果该字符是有效数字,该方法将查看位置1处的字符,进行同样的测试。这一过程将持续到发现非有效数字的字符为止,此时parseInt()将把该字符之前的字符串转换成数字。
例如,如果要把字符串 "12345red" 转换成整数,那么parseInt()将返回12345,因为当它检查到字符r 时,就会停止检测过程。
字符串中包含的数字字面量会被正确转换为数字,比如 "0xA" 会被正确转换为数字10。不过,字符串 "22.5" 将被转换成22,因为对于整数来说,小数点是无效字符。

var iNum1 = parseInt("12345red"); 
var iNum2 = parseInt("0xA"); 
var iNum3 = parseInt("56.9"); 
var iNum4 = parseInt("red"); 
document.write("iNum1="+iNum1);//返回12345 
document.write("iNum2="+iNum2);//返回10 
document.write("iNum3="+iNum3);//返回56 
document.write("iNum3="+iNum4);//返回NaN 
Copy after login

parseInt()方法还有基模式,可以把二进制、八进制、十六进制或其他任何进制的字符串转换成整数。基是由parseInt()方法的第二个参数指定的。

var iNum1 = parseInt("AF", 16); 
var iNum2 = parseInt("10", 2); 
var iNum3 = parseInt("10", 8); 
var iNum4 = parseInt("10", 10); 
document.write("iNum1="+iNum1);//返回175 
document.write("iNum2="+iNum2);//返回2 
document.write("iNum3="+iNum3);//返回8 
document.write("iNum4="+iNum4);//返回10 
Copy after login

2)parseFloat()方法
parseFloat()方法与parseInt()方法的处理方式相似,从位置0开始查看每个字符,直到找到第一个非有效的字符为止,然后把该字符之前的字符串转换成整数。不过,对于这个方法来说,第一个出现的小数点是有效字符。如果有两个小数点,第二个小数点将被看作无效的。parseFloat()会把这个小数点之前的字符转换成数字。这意味着字符串"11.22.33"将被解析成11.22。
使用parseFloat()方法的另一不同之处在于,字符串必须以十进制形式表示浮点数,而不是用八进制或十六进制。该方法会忽略前导0,所以八进制数0102 将被解析为102。对于十六进制数0xA,该方法将返回 NaN,因为在浮点数中,x不是有效字符。此外,parseFloat() 方法也没有基模式。
下面是使用 parseFloat() 方法的一些示例:

var fNum1 = parseFloat("12345red"); 
var fNum2 = parseFloat("0xA"); 
var fNum3 = parseFloat("11.2"); 
var fNum4 = parseFloat("11.22.33"); 
var fNum5 = parseFloat("0102"); 
var fNum6 = parseFloat("red"); 
document.write("iNum1="+iNum1);//返回12345 
document.write("iNum2="+iNum2);//返回NaN 
document.write("iNum3="+iNum3);//返回11.2 
document.write("iNum4="+iNum4);//返回11.22 
document.write("iNum5="+iNum5);//返回102 
document.write("iNum6="+iNum6);//返回NaN 
Copy after login

(3)强制类型转换
使用强制类型转换来处理转换值的类型。使用强制类型转换可以访问特定的值,即使它是另一种类型的。ECMAScript 中可用的3种强制类型转换如下:

  • 1)Boolean(value) - 把给定的值转换成 Boolean 型;
  • 2)Number(value) - 把给定的值转换成数字(可以是整数或浮点数);
  • 3)String(value) - 把给定的值转换成字符串;

这些应该很好理解,在学习那些高级程序设计语言的时候经常会能使用到这些。
四、引用类型
引用类型通常叫做类,也就是说,遇到引用值,所处理的就是对象。从传统意义上来说,ECMAScript并不真正具有类。事实上,除了说明不存在类,在ECMA-262中根本没有出现“类”这个词。ECMAScript定义了“对象定义”,逻辑上等价于其他程序设计语言中的类。
对于JS对象的详细解释在前面的博文中也有,参考:轻松学习JavaScript九:JavaScript对象和数组。
我们再来了解一个判断引用类型的操作符instanceof,在使用typeof运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。ECMAScript引入了另一个Java运算符 instanceof 来解决这个问题。instanceof运算符与typeof运算符相似,用于识别正在处理的对象的类型。与typeof方法不同的是,instanceof方
法要求开发者明确地确认对象为某特定类型。
例如:

var oStringObject = new String("hello world"); 
document.write(oStringObject instanceof String);//输出 "true" 
Copy after login

这段代码问的是“变量oStringObject是否为 String 对象的实例?”oStringObject的确是 String对象的实例,因此结果是 "true"。尽管不像typeof方法那样灵活,但是在typeof方法返回 "object" 的情况下,instanceof方法还是很有用的。
此外,ECMAScript还有伪对象一说,也就是其他的基本类型,使用new创建时也是可以作为对象的,比如:String对象,Boolean对象和Number对象。它们是基本类型的引用类型。详细了解参考:ECMAScript引用类型。ECMAScript还包含了许多对象,本地对象,内置对象和宿主对象。这些我们会在后面的面向对象的时候具体了解。
五、复制变量值
在变量复制方面,基本类型和引用类型有所不同,基本类型是复制的是值本身,而引用类型复制的是地址。
我们来看具体的实例:

var box="Lee"; 
var box2=box; 
box2="Amy";//重新赋值后,两个基本类型变量操作时互不影响,还是保持各自的独立性 
document.write("box2="+box2+"<br/>"); 
document.write("box="+box); 
Copy after login

输出的结果为:Amy
Lee

var box=new Object(); 
box.name="Lee"; 
var box2=box;//把引用地址值复制给box2 
box2.name="Amy";//重新赋值后,两个引用类型都指向同一个对象。name属性只要发生改变都会更改原值。 
document.write(" box2.name="+box2.name+"<br/>"); 
document.write("box.name="+box.name); 
Copy after login

输出的结果为:Amy
                       Amy

以上就是关于JavaScript基本类型和引用类型的详细介绍,希望对大家的学习有所帮助。

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

How do generic functions handle pointers and reference types in Golang? How do generic functions handle pointers and reference types in Golang? Apr 16, 2024 pm 04:06 PM

When a generic function handles pointer types in Go, it will receive a reference to the original variable, allowing the variable value to be modified. Reference types are copied when passed, making the function unable to modify the original variable value. Practical examples include using generic functions to compare strings or slices of numbers.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

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

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles