Javascript 简明教程

JavaScript - Data Types

JavaScript Data Types

JavaScript 中的数据类型是指我们存储或处理的值的类型。编程语言最基本的一个特点就是它所支持的 data types 。这些类型是可以表示和在编程语言中处理的值的类型。

Data types in JavaScript referes to the types of the values that we are storing or working with. One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

JavaScript 数据类型可以分为原始和非原始(对象)。JavaScript (ES6 及更高版本) 允许您使用七种 primitive data types

JavaScript data types can be categorized as primitive and non-primitive (object). JavaScript (ES6 and higher) allows you to work with seven primitive data types

  1. Strings of text e.g. "This text string" etc.

  2. Numbers, eg. 123, 120.50 etc.

  3. Boolean e.g. true or false.

  4. null

  5. undefined

  6. BigInt

  7. Symbol

BigIntSymbol 在 ES6 中引入。在 ES5 中,只有五种原始数据类型。

BigInt and Symbol are introduced in ES6. In ES5, there were only five primitive data types.

除了这些原始数据类型之外,JavaScript 还支持一种称为对象的 composite data type 。我们将在一个单独的章节中详细介绍对象。

In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter.

Object 数据类型包含 3 种子数据类型 −

The Object data type contains the 3 sub-data types −

  1. Object

  2. Array

  3. Date

Why are data types important?

在任何一种编程语言中,数据类型对于操作执行都至关重要。

In any programming language, data types are important for operation manipulation.

例如,以下代码生成了“1010”输出。

For example, the below code generates the “1010” output.

let sum = "10" + 10;

在此示例中,JavaScript 引擎将第二个运算符转换为字符串,并使用“+”运算符对其进行组合,而不是将其相加。

Here, the JavaScript engine converts the second operand to a string and combines it using the '+' operator rather than adding them.

所以,你需要确保运算符的类型是正确的。

So, you need to ensure that the type of operands is correct.

现在,让我们通过示例来学习每种数据类型。

Now, let’s learn about each data type with examples.

JavaScript String

在 JavaScript 中,字符串是字符的序列,可以使用下面给出的 3 种不同方法来创建:

In JavaScript, the string is a sequence of characters and can be created using 3 different ways given below −

  1. Using the single quote

  2. Using the double quote

  3. Using the backticks

Example

在下面的示例中,我们使用单引号、双引号和反引号创建了字符串。在输出中,它为所有 3 个字符串打印了相同的结果。

In the example below, we have created strings using single quotes, double quotes, and backticks. In the output, it prints the same result for all 3 strings.

<html>
<head>
   <title> JavaScript string </title>
</head>
<body>
   <script>
      let str1 = "Hello World!"; // Using double quotes
      let str2 = 'Hello World!'; // Using single quotes
      let str3 = `Hello World!`; // Using backticks
      document.write(str1 + "<br>");
      document.write(str2 + "<br>");
      document.write(str3 + "<br>");
   </script>
</body>
</html>

JavaScript Number

JavaScript 数字总是存储为 floating-point 值(十进制数字)。

A JavaScript number is always stored as a floating-point value (decimal number).

JavaScript 不区分 integer 值和 floating-point 值。

JavaScript does not make a distinction between integer values and floating-point values.

JavaScript 使用由 IEEE 754 标准定义的 64-bit 浮点格式表示数字。

JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

Example

在下面的示例中,我们演示了带和小数点的 JavaScript 数字。

In the example below, we demonstrate JavaScript numbers with and without decimal points.

<html>
<head>
   <title> JavaScript number </title>
</head>
<body>
   <script>
      let num1 = 10; // Integer
      let num2 = 10.22; // Floating point number
      document.write("The value of num1 is " + num1 + "<br/>");
      document.write("The value of num2 is " + num2);
   </script>
</body>
</html>

Example (Exponential notation of numbers)

JavaScript 还支持数字的指数表示法。我们在下面的示例代码中对此进行了说明:

JavaScript also support exponential notaion of numbers. We have explained this in the below example code −

<html>
<head>
   <title> JavaScript number Exponential notation </title>
</head>
<body>
   <script>
      let num1 = 98e4;    // 980000
      let num2 = 98e-4;   // 0.0098
      document.write("The value of num1 is: " + num1 + "<br/>");
      document.write("The value of num2 is: " + num2);
   </script>
</body>
</html>

JavaScript Boolean

在 JavaScript 中, Boolean 数据类型只有两个值: truefalse

In JavaScript, the Boolean data type has only two values: true or false.

<html>
<head>
   <title> JavaScript Boolean </title>
</head>
<body>
   <script>
      let bool1 = true;
      let bool2 = false;
      document.write("The value of the bool1 is " + bool1 + "<br/>");
      document.write("The value of the bool2 is " + bool2 + "<br/>");
   </script>
</body>
</html>

JavaScript Undefined

当声明变量但未对其进行初始化时,它将包含 undefined 值。但是,你还可以手动将未定义的值分配给变量。

When you declare a variable but don’t initialize it, it contains an undefined value. However, you can manually assign an undefined value to the variable also.

<html>
<head>
   <title> JavaScript Undefined </title>
</head>
<body>
   <script>
      let houseNo; // Contains undefined value
      let apartment = "Ajay";
      apartment = undefined; // Assigning the undefined value
      document.write("The value of the house No is: " + houseNo + "<br/>");
      document.write("The value of the apartment is: " + apartment + "<br/>");
   </script>
</body>
</html>

JavaScript Null

当任何变量的值未知时,你可以使用 null 。对于空值或未知值,最好使用 null 而不是未定义值。

When any variable’s value is unknown, you can use the null. It is good practice to use the null for the empty or unknown value rather than the undefined one.

<html>
<head>
   <title> JavaScript null </title>
</head>
<body>
   <script>
      let houseNo = null; // Unknown house number
      let apartment = "B-2";
      appartment = null; // Updating the value to null
      document.write("The value of the houseNo is: " + houseNo + "<br/>");
      document.write("The value of the apartment is: " + apartment + "<br/>");
   </script>
</body>
</html>

JavaScript Bigint

JavaScript 仅存储 64 位长的浮点数。如果你想要存储一个非常大的数字,你应该使用 Bigint 。你可以通过在数字的末尾追加 n 来创建 BigInt。

JavaScript stores only 64-bit long floating point numbers. If you want to store a very large number, you should use the Bigint. You can create Bigint by appending n to the end of the number.

<html>
<head>
   <title> JavaScript Bigint </title>
</head>
<body>
   <script>
      let largeNum = 1245646564515635412348923448234842842343546576876789n;
      document.write("The value of the largeNum is " + largeNum + "<br/>");
   </script>
</body>
</html>

JavaScript Symbol

Symbol 数据类型是在 JavaScript 的 ES6 版本中引入的。它用于创建唯一的原始不可变值。

The Symbol data type is introduced in the ES6 version of JavaScript. It is used to create unique primitive, and immutable values.

Symbol() 构造函数可用于创建唯一符号,并且你可以将字符串作为 Symbol() 构造函数的参数传递。

The Symbol() constructor can be used to create a unique symbol, and you may pass the string as a parameter of the Symbol() constructor.

Example

在下面的示例中,我们为同一个字符串创建了 sym1 和 sym2 符号。之后,我们比较了 sym1 和 sym2 的值,结果为 false。这意味着这两个符号都是唯一的。

In the example below, we created the sym1 and sym2 symbols for the same string. After that, we compared the value of sym1 and sym2, and it gave a false output. It means both symbols are unique.

<html>
<head>
   <title> JavaScript Symbol </title>
</head>
<body>
   <script>
      let sym1 = Symbol("123");
      let sym2 = Symbol("123");
      let res = sym1 === sym2;
      document.write("Is sym1 and Sym2 are same? " + res + "<br/>");
   </script>
</body>
</html>

JavaScript Object

在 JavaScript 中, object 数据类型允许我们以 key-value 格式存储数据集合。有多种方法来定义对象,我们将在对象一章中看到。

In JavaScript, the object data type allows us to store the collection of the data in the key-value format. There are multiple ways to define the object, which we will see in the Objects chapter.

这里,我们将使用对象字面量创建一个对象。

Here, we will create an object using the object literals.

Example

在下例中,我们用 '{}'(对象字面量)创建了一个 obj 对象。该对象包含带字符串值的 'animal' 属性、带数字值的 'legs' 属性,并将 'color' 变量的值分配给 'hourseColor' 属性。

In the example below, we used the '{}' (Object literals) to create an obj object. The object contains the 'animal' property with the string value, the 'legs' property with the number value, and the value of the 'color' variable is assigned to the 'hourseColor' property.

JSON.stringify() 方法将对象转换为字符串并在输出中显示。

The JSON.stringify() method converts the object to strings and shows it in the output.

<html>
<head>
   <title> JavaScript Object </title>
</head>
<body>
   <script>
      let color = "Brown";
      const obj = {
         animal: "Hourse",
         legs: 4,
         hourseColor: color
      }
      document.write("The given object is: " + JSON.stringify(obj) + "<br/>");
   </script>
</body>
</html>

JavaScript Array

在 JavaScript 中, array 是不同数据类型的元素列表。可以使用两个方括号 '[]' 创建数组,并在数组中插入多个用逗号分隔的值。

In JavaScript, the array is a list of elements of the different data types. You can create an array using two square brackets '[]' and insert multiple comma seprated values inside the array.

<html>
<head>
   <title> JavaScript Array </title>
</head>
<body>
   <script>
      const colors = ["Brown", "red", "pink", "Yellow", "Blue"];
      document.write("The given array is: " + colors + "<br/>");
   </script>
</body>
</html>

JavaScript Date

可以使用 JavaScript Date object 来操作日期。

You can use the JavaScript Date object to manipulate the date.

Example

在下例中,我们使用了 Date() 构造函数来创建日期。在输出中,你可以根据你的时区看到当前日期和时间。

In the example below, we used the Date() constructor to create a date. In the output, you can see the current date and time according to your time zone.

<html>
<head>
   <title> JavaScript Date </title>
</head>
<body>
   <script>
      let date = new Date();
      document.write("The today's date and time is: " + date + "<br/>");
   </script>
</body>
</html>

Dynamic Types

JavaScript 是一种像 Python 和 Ruby 之类的 dynamically typed 语言。因此,它在运行时决定变量的数据类型,而不是在编译时。我们可以对 JavaScript 变量初始化任意数据类型的值,或重新给它们赋值。

JavaScript is a dynamically typed language like Python and Ruby. So, it decides the variable’s data type at the runtime but not at the compile time. We can initialize or reassign the value of any data type to the JavaScript variables.

Example

在下例中,我们用字符串值初始化了第一个变量。然后,我们将其值更新为数字和布尔值。

In the example below, we initialized the first variable with the string value. After that, we updated its values to the number and boolean value.

<html>
<head>
   <title> JavaScript dynamic data type </title>
</head>
<body>
   <script>
      let first = "One"; // it is string
      first = 1; // now it's Number
      document.write("The value of the first variable is " + first + "<br/>");
      first = true; // now it's Boolean
      document.write("The value of the first variable is " + first + "<br/>");
   </script>
</body>
</html>

Checking Data Types Using the typeof Operator

typeof 运算符允许你检查变量的类型。

The typeof operator allows you to check the type of the variable.

Example

在下例中,我们用 typeof 运算符检查了各种变量的数据类型。

In the below example, we used the typeof operator to check the data type of the various variables.

<html>
<head>
   <title> typeof operator </title>
</head>
<body>
   <script>
      let num = 30;
      let str = "Hello";
      let bool = true;
      document.write("The data type of num is: " + typeof num + "<br/>");
      document.write("The data type of str is: " + typeof str + "<br/>");
      document.write("The data type of bool is: " + typeof bool + "<br/>");
   </script>
</body>
</html>