I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.

Lesson Objective for today

Yesterday, based on some page search, I learned the grammar and variables of ES basic concepts in chapter 3 of JavaScirpt Advanced Programming (3rd edition). Today, I mainly learn the basic data types of ES basic concepts in chapter 3 based on search. It is also a day for learning, come on, small and !!!!

The original plan was to use one article for the release, but the release kept prompting Request Entity Too Large, so it was released in two articles ~~~

The summary of today’s learning is in the first article, and the summary is in the second ~~~~

BigInt

what

BigInt is a built-in object that provides a way to represent integers greater than 2-1. This was originally the largest Number that could be represented as Number in Javascript. BigInt can represent an arbitrarily large integer.

You can define a BigInt by adding n to an integer literal, such as 10n, or by calling BigInt().

const theBiggestInt = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991);
/ / ↪ 9007199254740991 n
const hugeString = BigInt("9007199254740991");
/ / ↪ 9007199254740991 n
const hugeHex = BigInt("0x1fffffffffffff");
/ / ↪ 9007199254740991 n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
/ / ↪ 9007199254740991 n
Copy the code

It is similar to Number in some ways, but has several key differences: it cannot be used for methods in Math objects; Cannot be mixed with any Number instances; both must be converted to the same type.

Be careful when converting back and forth between the two types, as the BigInt variable can lose precision when converting to the Number variable.


grammar

The type information

When typeof tests are used, the BigInt object returns “BigInt” :

typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true
Copy the code

With Object wrapping, BigInt is considered a plain “Object” :

typeof Object(1n) === 'object'; // true
Copy the code

operation

The following operators can be used with BigInt: +, *, -, **, %. Bitwise operations other than >>> (unsigned right shift) are also supported. Since BigInt is signed, >>> (unsigned right shift) cannot be used for BigInt. To be compatible with ASM.js, BigInt does not support the monocular (+) operator.

const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
/ / ↪ 9007199254740991 n
const maxPlusOne = previousMaxSafe + 1n;
/ / ↪ 9007199254740992 n
Copy the code

const theFuture = previousMaxSafe + 2n; // ↪ 9007199254740993n, this works now! const multi = previousMaxSafe * 2n; / / ↪ 18014398509481982 n constSubtr = multi -10n; / / ↪ 18014398509481972 n const mod = multi % 10n; / / ↪ 2 n const bigN = 2n ** 54n; / / ↪ 18014398509481984 n bigN * - 1n N. / / ↪ - 18014398509481984

The/operator is also fine for integer operations. However, because these variables are BigInt and not BigDecimal, the result of the operator is rounded to zero, meaning that the decimal part is not returned. When BigInt is used, decimals are rounded.

const expected = 4n / 2n;
/ / ↪ 2 n
const rounded = 5n / 2n;
// ↪ 2n, not 2.5n
Copy the code

To compare

BigInt and Number are not strictly equal, but loosely equal.

0n === 0
/ / ↪ false
0n == 0
/ / ↪ true
Copy the code

Number and BigInt can be compared.

1n < 2
/ / ↪ true
2n > 1
/ / ↪ true
2 > 2
/ / ↪ false
2n > 2
/ / ↪ false
2n >= 2
/ / ↪ true
Copy the code

They can also be mixed together in an array and sorted.

const mixed = [4n, 6.- 12n, 10.4.0.0n];
// ↪ [4n, 6, -12n, 10, 4, 0, 0n]
mixed.sort();
// ↪ [-12n, 0, 0n, 10, 4n, 4, 6]
Copy the code

Note that BigInts wrapped in Object are compared using Object’s comparison rules, and only the same objects are equal when compared.

0n === Object(0n); // false
Object(0n) === Object(0n); // false
const o = Object(0n);
o === o // true
Copy the code



conditions

BigInt behaves like Number when it needs to be converted to Boolean. Used for Logical Operators | |, &&, and! Operands of; Or in conditional statements such as if statement.

if (0n) {
  console.log('Hello from the if! ');
} else {
  console.log('Hello from the else! ');
}
// ↪ "Hello from the else!"
0n || 12n
/ / ↪ 12 n
0n && 12n
/ / ↪ 0 n
Boolean(0n)
/ / ↪ false
Boolean(12n)
/ / ↪ true
!12n
/ / ↪ false
!0n
/ / ↪ true
Copy the code



example

Calculate a prime number

function isPrime(p) {
  for (let i = 2n; i * i <= p; i++) {
    if (p % i === 0n) return false;
  }
  return true;
}

// Takes a BigInt as an argument and returns a BigInt
function nthPrime(nth) {
  let maybePrime = 2n;
  let prime = 0n;

while (nth >= 0n) { if (isPrime(maybePrime)) { nth -= 1n; prime = maybePrime; } maybePrime += 1n; }

Copy the code

return prime; } nthPrime(20n) / / ↪ 73 n


tip

conversion

Because converting between Number and BigInt loses accuracy, it is recommended to use BigInt only when the value is likely to be greater than 2, and not to convert between the two types.


cryptography

Since operations on BigInt are not constant time, BigInt is not suitable for use in cryptography.


Use in JSON

Using json.stringify () on any BigInt value raises TypeError because BigInt values are not serialized in JSON by default. However, the toJSON method can be implemented if desired:

BigInt.prototype.toJSON = function() { return this.toString(); }
Copy the code

Json.stringify now generates the following string instead of throwing an exception:

JSON.stringify(BigInt(1));
/ / '" 1"
Copy the code

String

what

The String global object is a constructor for a String or a sequence of characters.


attribute


String.prototypeAttributes of attributes:
writable false
enumerable false
configurable false

grammar

String literals

The string can be any text in quotes. You can use single or double quotes, and you can use quotes within strings, as long as they don’t match the quotes surrounding the string.

'string text' 
"string text"
"Chinese/Chinese" 
"español"
"English "
"ह ि न ् द ी"
"An ل ع ر ب ي ة"
"português"
"ব া ং ল া"
"р с с seem и й" 
"Japanese"
"ਪ ੰ ਜ ਾ ਬ ੀ"
"국어"
Copy the code

String object

  • Syntax for creating strings
String(thing)
new String(thing)
Copy the code
  • parameter

Thing Any value that can be converted to a string.


Template literals

As of ECMAScript 2015, string literals can also be called template literals

`hello world` `hello! world! ` `hello ${who}` escape `<a>${who}</a>`
Copy the code

Escape character

In addition to ordinary printable characters, special characters with special functions can be put into a string by escaping characters

Code Output
\ 0 Null character
\ ' Single quotes
\" Double quotation marks
\ \ The backslash
\n A newline
\r enter
\v Vertical TAB character
\t Horizontal TAB character
\b backspace
\f Change the page
\uXXXX Unicode code
\u{X}.\u{XXXXXX} unicode codepoint
\xXX Latin-1 character (x lowercase)

Unlike other languages, javascript strings do not distinguish between single and double quotes, so the escape character above will work for both single and double quoted strings.


A long string

Sometimes, your code may contain very long strings. You might want to write a string like this as multiple lines, rather than having the line stretch out indefinitely or be collapsed by the editor. There are two ways to do this. First, you can concatenate multiple strings using the + operator, as shown below

let longString = "This is a very long string which needs " +
                 "to wrap across multiple lines because " +
                 "otherwise my code is unreadable.";
Copy the code

Second, you can use the backslash character (” \ “) at the end of each line to indicate that the string will continue on the next line. Make sure backslashes are not followed by Spaces or any characters other than newlines or indents; Otherwise the backslash will not work. As shown below.

let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
Copy the code

Using both methods creates the same string.


example

Gets a single character from a string

There are two ways to get a character from a string. The first is to use the charAt method

return 'cat'.charAt(1); // returns "a"
Copy the code

The other (described in ECMAScript 5) is to treat a string as an array-like object, where each character corresponds to a numeric index

return 'cat'[1]; // returns "a"
Copy the code

A string accessed in parentheses cannot be deleted or added to because the unknown attributes of the string are not readable or configured. (See Object.defineProperty for more information.)


String comparison

C savvy developers often use the STRCMP function to compare strings, but in JavaScript you just use the comparison operator (>/=/<=)

var a = "a";
var b = "b";
if (a < b) // true
  print(a + " is less than " + b);
else if (a > b)
  print(a + " is greater than " + b);
else
  print(a + " and " + b + " are equal.");
Copy the code

Using the localeCompare method inherited from the string instance can achieve the same effect.


tip

The difference between basic strings and string objects ~~~

Be careful to distinguish between JavaScript string objects and primitive string values. (The same goes for Boolean and Numbers.) String literals (defined by single or double quotes) and strings that call the String method directly (without generating an instance of a String object through new) are basic strings. JavaScript automatically converts the base string to a string object, and you can only use the string object methods once you have converted the base string to a string object. When the base string needs to call a string object’s method or query value (which the base string doesn’t have), JavaScript automatically converts the base string to a string object and calls the corresponding method or executes a query.

var s_prim = "foo";
var s_obj = new String(s_prim);
console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj);  // Logs "object"
Copy the code

When eval is used, the base string and the string object also produce different results. Eval treats the base string as source code; String objects are treated as objects and returned as objects. Such as:

s1 = "2 + 2";               // creates a string primitive
s2 = new String("2 + 2");   // creates a String object
console.log(eval(s1));      // returns the number 4
console.log(eval(s2));      // returns the string "2 + 2"
Copy the code

For these reasons, using a string object when a piece of code needs to use a basic string can cause execution to fail (although programmers generally don’t need to worry about this). Using the valueOf method, we can convert a string object to its corresponding primitive string.

console.log(eval(s2.valueOf())); // returns the number 4
Copy the code

Note: StringView — a C-like representation of strings based on typed arrays can be used to convert string objects to primitives.


Symbol

what

Symbol is a primitive data type.

Each Symbol value returned from Symbol() is unique. A symbol value can be used as an identifier for object properties; This is the only purpose of this data type. See Glossary Entry for Symbol for a further explanation.

const symbol1 = Symbol(a);const symbol2 = Symbol(42);
const symbol3 = Symbol('foo');

console.log(typeof symbol1);
// expected output: "symbol"

console.log(symbol3.toString());
// expected output: "Symbol(foo)"

console.log(Symbol('foo') = = =Symbol('foo'));
// expected output: false
Copy the code




attribute

Symbol.prototypeAttributes of attributes:
writable false
enumerable false
configurable false

grammar

Create a Symbol object

Symbol([description])
Copy the code

parameter

Description This parameter is optional. The value is a string. A description of a symbol that can be used to debug but not access the symbol itself.


example

Use the Typeof operator on symbol

The Typeof operator helps you identify the symbol type

typeof Symbol() = = ='symbol'
typeof Symbol('foo') = = ='symbol'
typeof Symbol.iterator === 'symbol'
Copy the code

Symbols and the for… In the iteration

Symbols in the for… The in iteration is not enumerable. . In addition, the Object getOwnPropertyNames () will not return to symbol attribute of an Object, but you can use the Object. GetOwnPropertySymbols () to get them.

var obj = {};
obj[Symbol("a")] = "a";
obj[Symbol.for("b")] = "b";
obj["c"] = "c";
obj.d = "d";
for (var i in obj) {
   console.log(i); // logs "c" and "d"
}
Copy the code

Symbols and JSON. Stringify ()








JSON.stringify({[Symbol("foo")]: "foo"});                 
/ / '{}'
Copy the code

For more details, see json.stringify ().


Symbol wrapper object as the key of the property








var sym = Symbol("foo");
var obj = {[sym]: 1};
obj[sym];            / / 1
obj[Object(sym)];    // still 1
Copy the code

tip

Create a new Symbol type directly using Symbol() and describe it with an optional string.

var sym1 = Symbol(a);var sym2 = Symbol('foo');
var sym3 = Symbol('foo');
Copy the code

The above code creates three new Symbol types. Note that Symbol(“foo”) does not force the string “foo” to be converted to Symbol type. It creates a new symbol type each time:

Symbol("foo") = = =Symbol("foo"); // false
Copy the code

The following syntax with the new operator raises TypeError:

var sym = new Symbol(a);// TypeError
Copy the code

This prevents the creation of an explicit Symbol wrapper object instead of a Symbol value. Creating an explicit wrapper object around a primitive data type is no longer supported as of ECMAScript 6. However, existing primitive wrapper objects such as New Boolean, New String, and New Number can still be created for legacy reasons. If you really want to create a Symbol wrapper object, you can use the object () function:

var sym = Symbol("foo");
typeof sym;     // "symbol"
var symObj = Object(sym);
typeof symObj;  // "object"
Copy the code

Globally shared Symbol









Look for the Symbol property in the object

Object. GetOwnPropertySymbols () method to let you in the search for a given Object returns a symbol attribute? An array of type symbol. Note that each initialized object does not have its own Symbol attribute, so this array may be empty unless you have already set the symbol attribute on the object.


Symbol type conversion






Summary of today’s lesson



Today the mood

I have learned seven basic data types in ES basic concepts today, and I feel very good. I hope to learn more tomorrow ~~~~


This article is formatted using MDNICE