Data Types

JavaScript Data Types (JavaScript数据类型)

Data types

Data types (数据类型)

JavaScript is a dynamic type language, which means that you don’t need to define type of the variable because it is effectively used by the JavaScript engine. There are two types of data in JavaScript: primitive data type and non-primitive (reference) data type.

A variable in JavaScript contains any of these data types: strings, numbers, objects:

let length = 17;                               // Number
let lastName = "Jameson";                      // String
let x = {firstName:"John", lastName:"Doe"};    // Object

Programming languages which allow this kind of things are called “dynamically typed”, when there are data types, but variables aren’t bound to any of them. (当有数据类型时,允许这种事情的编程语言被称为“动态类型” ,但变量并不绑定到它们中的任何一个。)

There are 7 primitive data types in JavaScript:

  • Number (编号)

  • Bigint (bigint)

  • String (字符串)

  • Boolean (布尔)

  • Null (null)

  • Undefined (- 未定義的 -)

  • Symbol (符号)

  • and Object is a non-primitive data type (-和Object是一个非原始数据类型)

Primitive values

Primitive values (原始值)

All mentioned above types are incapable of being changed except objects. For example, Strings are unchangeable, so we call them “primitive values”. (除了对象之外,上述所有类型都无法更改。例如,字符串是不可更改的,因此我们称之为“原始值”。)

Number

Number (编号)

The Number type are integer and floating point numbers. (数字类型是整数和浮点数。)

There are many operations for numbers: addition +, subtraction -, multiplication*, division / and others.

let num1 = 32;
let num2 = +Infinity;

We can write numbers with or without a decimal point. They can also be +Infinity, -Infinity, and NaN (not a number). (我们可以写有或没有小数点的数字。它们也可以是+ Infinity、-Infinity和NaN (不是数字)。)

Infinity represents the mathematical Infinity ∞, which is a special value that’s bigger than any number. We can get it dividing by zero:

console.log( 1 / 0 ); // Infinity

NaN is a computational error, which is a result of an incorrect or an undefined mathematical operation, for example:

console.log( "not a number" / 2 ); // NaN, such division is erroneous

Any operation on NaN returns NaN:

console.log( "not a number" / 2 + 5 ); // NaN

NaN in a mathematical expression can influences to the whole result. (数学表达式中的NaN可以影响整个结果。)

More information about working with numbers you can find in Numbers. (有关使用数字的更多信息,请参阅数字。)

BigInt

BigInt (bigint)

In JavaScript the BigInt type is a numeric primitive that can represent whole number with random exactness. BigInt gives you an opportunity safely store and operate on large integers even beyond the safe integer limit for Numbers. (在JavaScript中, BigInt类型是一个数字原语,可以表示具有随机精度的整数。BigInt为您提供了一个安全存储和操作大整数的机会,甚至超出了数字的安全整数限制。)

In JavaScript, the “number” type can’t represent integer values, which are larger than 253 or less than -253 for negatives. It is a technical limitation caused by their internal representation. That’s about 16 decimal digits, but sometimes we need really big numbers, e.g. for cryptography or microsecond-precision timestamps. (在JavaScript中, “数字”类型不能表示整数值,对于负数,整数值大于253或小于-253。这是由其内部陈述造成的技术限制。这大约是16位十进制数字,但有时我们需要非常大的数字,例如用于加密或微秒精度时间戳。)

const bigint = 8562323159475639012345678901234567890n;
const sameBigint = BigInt("8562323159475639012345678901234567890");
const bigintNumber = BigInt(10); // same as 10n

BigInt type was added to the language not long ago and it represents integers of arbitrary length. A BigInt is created by added n to the end of an integer literal:

const bigint = 8562323159475639012345678901234567890n;
console.log(bigint);

Click BigInt to find more information about working with BigInt. (单击BigInt以查找有关使用BigInt的更多信息。)

String

String (字符串)

We use strings for storing text. In JavaScript, strings can’t be changed, and they must be inside of either double or single quotes. (我们使用字符串来存储文本。在JavaScript中,字符串不能更改,它们必须在双引号或单引号内。)

let str = "Hello";
let str2 = 'Welcome to w3cdoc!';
let phrase = `${str} dear friend`;
console.log(str);
console.log(str2);
console.log(phrase);

There are 3 types of quotes in JavaScript:

Double quotes:“Welcome”. Single quotes: ‘Welcome’. Backticks: Welcome.

Double and single quotes are “simple” quotes, practically there is no difference between them in JavaScript. Backticks are “extended functionality” quotes that allow us to embed variables and expressions into a string by wrapping them in ${…}, for instance:

Example of the embed a variable in string:

let name = "w3cdoc";
// embed a variable
console.log( `Welcome to ${name}!` ); // Welcome to w3cdoc!

Example of the embed an expression in string:

console.log( `the result is ${5 + 3}` ); // the result is 8

The expression inside ${…} is assessed, it’s result usually becomes a part of the string. We can put anything in there: name, an arithmetical expression or something more complex.

But it can only be done in backticks, other quotes don’t have this embedding functionality. (但它只能在反引号中完成,其他引用不具有此嵌入功能。)

console.log( "the result is ${2 + 5}" );

This example returns string - “the result is ${2 + 5}” ,here you don’t need the double quotes.

We’ll see more about working with strings in the chapter Strings. (我们将在字符串一章中看到有关使用字符串的更多信息。)

Boolean

Boolean (布尔)

Boolean is a datatype which has just two values: true or false. Boolean is used in JavaScript as a function for getting the value of an object, variables, expressions, conditions, etc. This type is used to store yes/no values, where true means “yes, correct”, and false means “no, incorrect”.

In the example x1 and x2 stores the boolean value i.e. true and false:

let x1 = true;
let x2 = false;

Initialized below variables with strings are not boolean values:

let x1 ="true"; // not boolean values, it’s a string
let x2 ="false"; // not boolean values, it’s a string

Boolean values also can be as a result of comparisons:

let isSmaller = 5 < 3;
console.log( isSmaller ); //false (the comparison result is "no")

We’ll cover strings more thoroughly in Boolean. (我们将用布尔值更全面地介绍字符串。)

Null

Null (空)

It is one of JavaScript’s primitive values which is treated as falsy for boolean operations. In JavaScript null means “nothing”, “empty”. it’s something that doesn’t exist. (它是JavaScript的原始值之一,对于布尔运算被视为伪值。在JavaScript中, null表示“无”、“空”。它是不存在的东西。)

But in JavaScript, the data type of null is an object, which you can empty by setting an object to null:

let price = null;

The code above declares that price is unknown or empty for some reason. (上面的代码声明由于某种原因价格未知或为空。)

Undefined

Undefined (未定义)

The special value undefined makes a type of its own, just like null. In JavaScript, a variable without a value called undefined. It’s value and type are undefined, which means that the “value is not assigned”:

let x;
console.log(x); // shows "undefined"

Yet, technically, it is possible to assign undefined to any variable:

let x = 123;
x = undefined;
console.log(x); // "undefined"

But we don’t recommend doing that. Usually, we use null to assign an “unknown” or “empty” value to a variable, and we use undefined for checking if a variable has been assigned. (但我们不建议您这样做。通常,我们使用null为变量分配“未知”或“空”值,并使用undefined检查是否已分配变量。)

Symbol

Symbol (符号)

A Symbol is an immutable primitive value that is unique and can be used as the key of an Object property. In some programming languages, Symbols are called “atoms”. (Symbol是一个不可变的原始值,它是唯一的,可以用作Object属性的键。在一些编程语言中,符号被称为“原子”。)

A value which has the data type Symbol can be referred to as a “Symbol value”. A symbol value is created in a JavaScript by invoking the function Symbol, which produces an unnamed, unique value. A symbol can be used as an object property. (具有数据类型Symbol的值可以称为“符号值”。通过调用函数Symbol在JavaScript中创建符号值,该函数生成一个未命名的唯一值。符号可以用作对象属性。)

A Symbol value represents a unique identifier. For example, two symbols with the same description:

let symbol1 = Symbol("symbol")
let symbol2 = Symbol("symbol")
console.log(symbol1 === symbol2) // returns "false"

In this example, console.log returns false. (在此示例中, console.log返回false。)

Symbols have to be unique, even if we create a lot of symbols with the same description, they are different values. (符号必须是唯一的,即使我们创建了许多具有相同描述的符号,它们也是不同的值。)

You can find more information in Symbol. (您可以在符号中找到更多信息。)

Object

Object (对象)

We use objects to store keyed collections of various data and more complicated entities. In JavaScript, objects pass through almost every aspect of the language. First, we must understand them, then just go into depth. (我们使用对象来存储各种数据和更复杂实体的密钥集合。在JavaScript中,对象几乎通过语言的各个方面。首先,我们必须了解它们,然后深入研究。)

Object is not a primitive data type, it’s a collection of properties, which can reference any type of data, including objects and/or primitive values. Objects can be created with figure brackets {…} with a list of properties.

let obj = {
 key1: 'value1',
 key2: 'value2',
 key3: true,
 key4: 20,
 key5: {}
}

Let’s imagine that the object is a cabinet with signed files, where is stored every piece of data by the key. It’s rather easy to find a file by its name, add or remove a file. An empty object (“cabinet”) can be created with the help of one of two syntaxes:

let obj = new Object(); // "object constructor" syntax
let obj = {};  // "object literal" syntax

In this case we usually use the figure brackets {…} and call that declaration an object literal.

The typeof operator

The typeof operator (Typeof运算符)

typeof operator helps us to see which type is stored in a variable. It supports 2 forms of syntax:

  • As an operator: typeof x;

  • As a function: typeof(x);

It can work with or without parentheses, the result will be the same. The example below shows, that the call to typeof x returns a string with the type name:

console.log(typeof undefined); // "undefined"
console.log(typeof 0); // "number"
console.log(typeof 15n); // "bigint"
console.log(typeof false); // "boolean"
console.log(typeof "foo"); // "string"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof Math); // "object"  
console.log(typeof null); // "object"  
console.log(typeof prompt); // "function"
  • Math is a built-in object. Math provides mathematical operations.You can find more information about Math in Math. (-数学是一个内置对象。数学提供数学运算。您可以在数学中找到有关数学的更多信息。)

  • null is not an object, but the result of typeof null is “object”, which is an error in typeof. null is a special value with a separate type of its own. (- null不是对象,但typeof null的结果是“object” ,这是typeof中的错误。null是一个特殊值,具有自己的单独类型。)

  • The result of typeof prompt is “function”, because prompt is a function. We’ll study functions in Functions. Functions are the part of the object type, but typeof returning “function”. (- typeof提示符的结果是“function” ,因为提示符是一个函数。我们将学习函数中的函数。函数是对象类型的一部分,但typeof返回“function”。)

Type Conversions

Type Conversions (类型转换)

We can convert JavaScript variables to a new variable and another data type: using JavaScript function or automatically by JavaScript itself. For instance, alert automatically converts any value to a string to show it, mathematical operations convert values to numbers and so on.

Converting Numbers to Strings

Converting Numbers to Strings (将数字转换为字符串)

The global method String() can convert numbers to strings and can be used on any type of numbers, literals, variables, or expressions:

String(a);         // returns a string from a number variable a
String(100);       // returns a string from a number literal 100
String(20 + 30);  // returns a string from a number from an expression

We can also call the String(value) function to convert a value to a string:

let value = true;
console.log(typeof value); // boolean
value = String(value); // now value is a string "true"
console.log(typeof value); // string

Usually, string conversion is obvious: a false becomes “false”, null becomes “null” and so on.

Converting Booleans to Strings

Converting Booleans to Strings (将布尔值转换为字符串)

Boolean conversion is the most simple, which usually happens in logical operations but can also be performed with a call to Boolean(value). The global method String() has an ability to convert booleans to strings. (布尔转换是最简单的,通常发生在逻辑操作中,但也可以通过调用Boolean (值)来执行。全局方法String ()能够将布尔值转换为字符串。)

String(false);      // returns "false"
String(true);     // returns "true"

Here is some conversion rule:

The values which are intuitively “empty” (0, an empty string, null, undefined, and NaN) become false, other values become true. For example:

console.log( Boolean(1) ); // true
console.log( Boolean(0) ); // false
console.log( Boolean("hello") ); // true
console.log( Boolean("") ); // false

The string with zero “0” is true, as some languages (PHP) treat “0” as false. But in JavaScript, a non-empty string is always true. (> “0”为零的字符串为true ,因为某些语言( PHP )将“0”视为false。但在JavaScript中,非空字符串始终为true。)

console.log( Boolean("0") ); // true
console.log( Boolean(" ") ); // spaces, also true (any non-empty string is true)

Converting Dates to Strings

Converting Dates to Strings (将日期转换为字符串)

The global method String() converts dates to strings. (全局方法String ()将日期转换为字符串。)

console.log(String(Date()));  // returns "Tue Jan 21 2020 10:48:16  GMT+0200 (W. Europe Daylight Time)"

Converting Strings to Numbers

Converting Strings to Numbers (将字符串转换为数字)

The global method Number() converts strings to numbers. Strings containing numbers (like “5.20”) convert to numbers (like 5.20). Empty strings convert to 0. Anything else converts to NaN. (全局方法Number ()将字符串转换为数字。包含数字的字符串(如“5.20” )转换为数字(如5.20 )。空字符串转换为0。其他任何内容都会转换为NaN。)

Number("5.20");   // returns 5.20
Number(" ");      // returns 0
Number("");        // returns 0
Number("99 88");   // returns NaN

We meet numeric conversion in mathematical functions and expressions automatically. Example can be a division (/), which is applied to non-numbers:

console.log( "6" / "2" ); // 3, strings are converted to numbers

Number(value) function helps us explicitly convert a value to a number:

let str = "123";
console.log(typeof str); // string
let num = Number(str); // becomes a number 123
console.log(typeof num); // number

Explicit conversion is required when we read a value from a string-based source as a text form which expects a number to be entered. (当我们从基于字符串的源中读取需要输入数字的文本形式的值时,需要进行显式转换。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部