template string
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${
name}, how are you ${
time}?`
If a backtick is required in a template string, it must be escaped with a backslash.
let greeting = `\`Yo\` World!`;
Arbitrary JavaScript expressions can be placed inside the curly braces, which can perform operations and refer to object properties.
let x = 1;
let y = 2;
`${
x} + ${
y} = ${
x + y}`
// "1 + 2 = 3"
`${
x} + ${
y * 2} = ${
x + y * 2}`
// "1 + 4 = 5"
let obj = {
x: 1, y: 2};
`${
obj.x + obj.y}`
// "3"
String Add Method
Traditionally, JavaScript has only indexOf
methods that can be used to determine whether a string is contained within another string. ES6 provides three new methods.
includes(), startsWith(), endsWith()
includes()
: Returns a boolean indicating whether the argument string was found.startsWith()
: Returns a Boolean value indicating whether the parameter string is at the head of the original string.endsWith()
: Returns a Boolean value indicating whether the parameter string is at the end of the original string.
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
All three methods support a second parameter, which indicates where to start the search.
let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
The above code indicates that when the second parameter is used n
, endsWith
the behavior is different from the other two methods. It works on the first n
character, while the other two methods work from the first n
position until the end of the string.
-
repeat()
repeat
The method returns a new string, which means repeating the original stringn
.
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
If the parameter is a decimal, it will be rounded up.
'na'.repeat(2.9) // "nana"
If repeat
the argument is a string, it will be converted to a number first.
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"
-
padStart(),padEnd()
padStart()
For head completion,padEnd()
for tail completion.
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
padStart()
and padEnd()
accepts a total of two parameters, the first parameter is the maximum length of string completion, and the second parameter is the string used for completion.
If the length of the original string is equal to or greater than the maximum length, string completion will not take effect and the original string will be returned.
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
trimStart(),trimEnd()
trimStart()
trimEnd()
Eliminate leading spaces and trailing spaces in a string . They all returnnew string, does not modify the original string.
const s = ' abc ';
s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"
replaceAll()
String's instance methods replace()
can only replace the first match.
// replace()只将第一个b替换成了下划线。
'aabbcc'.replace('b', '_')
// 'aa_bcc'
// 如果要替换所有的匹配,不得不使用正则表达式的g修饰符。
'aabbcc'.replace(/b/g, '_')
// 'aa__cc'
'aabbcc'.replaceAll('b', '_')
// 'aa__cc'
BigInt data type
BigInt
It is only used to represent integers, there is no limit on the number of digits, and integers with any number of digits can be accurately represented.
const a = 2172141653n;
const b = 15346349309n;
// BigInt 可以保持精度
a * b // 33334444555566667777n
// 普通整数无法保持精度
Number(a) * Number(b) // 33334444555566670000
In order to Number
distinguish it from the type, BigInt
the data of the type must be suffixed n
.
1234 // 普通整数
1234n // BigInt
// BigInt 的运算
1n + 2n // 3n
BigInt and ordinary integer are two kinds of values, they are not equal.
42n === 42 // false
typeof
The operator BigInt
returns for data of type bigint
.
typeof 123n // 'bigint'
function extension
-
Basic usage
ES6 allows default values to be set for function parameters, that is, written directly after the parameter definition.
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello
Parameter variables are declared by default, so they cannot be used let
or const
declared again.
function foo(x = 5) {
let x = 1; // error
const x = 2; // error
}
rest parameters
ES6 introduces rest
parameters (in the form of ...变量名
), which are used to obtain redundant parameters of functions, so that arguments
objects do not need to be used. rest
The variable for parameter collocation is an array, which puts the redundant parameters into the array.
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2, 5, 3) // 10
In ES5, we generally use it as argument
a parameter, and arguments
the object is not an array, but an array-like object. So in order to use the array method, Array.from
it must be converted to an array first. rest
There is no such problem with parameters, it is a real array, and all methods unique to arrays can be used.
push
The following is an example of rewriting an array method with a rest parameter
function push(array, ...items) {
items.forEach(function(item) {
array.push(item);
console.log(item);
});
}
var a = [];
push(a, 1, 2, 3)
Note that rest
there can be no other parameters after the parameter (that is, it can only be the last parameter), otherwise an error will be reported.
arrow function
-
basic usage
(=>)
ES6 allows functions to be defined using "arrows" .
var f = v => v;
// 等同于
var f = function (v) {
return v;
};
If the arrow function takes no parameters or requires multiple parameters, use a single parenthesis to denote the parameter part.
var f = () => 5;
// 等同于
var f = function () {
return 5 };
var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2) {
return num1 + num2;
};
If the code block portion of an arrow function is more than one statement, enclose them in curly braces and usereturnstatement returns.
var sum = (num1, num2) => {
return num1 + num2; }
Arrow functions can be used in conjunction with variable destructuring.
const full = ({
first, last }) => first + ' ' + last;
// 等同于
function full(person) {
return person.first + ' ' + person.last;
}
Arrow functions make expressions more concise.
const isEven = n => n % 2 === 0;
const square = n => n * n;
One use of arrow functions is to simplify callback functions.
// 普通函数写法
[1,2,3].map(function (x) {
return x * x;
});
// 箭头函数写法
[1,2,3].map(x => x * x);
// 普通函数写法
var result = values.sort(function (a, b) {
return a - b;
});
// 箭头函数写法
var result = values.sort((a, b) => a - b);
rest
Parameters and 箭头函数
binding examples.
const numbers = (...nums) => nums;
numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]
const headAndTail = (head, ...tail) => [head, tail];
headAndTail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]
Notice:
- Arrow functions do not have their own
this
objects. (For ordinary functions, the internalthis
points to the object where the function is running, but this is not true for the arrow function. It does not have its ownthis
object, and the internal onethis
is defined in the upper scopethis
. That is to say, the internal arrow functionthis
The pointing is fixed, by contrast,this
the pointing of ordinary functions is mutable.) - Cannot be used as a constructor, that is, you cannot use
new
commands on arrow functions, otherwise an error will be thrown. (Arrow functions simplydoes not have its own this, causing the internal this to be the this of the outer code block. Precisely because it does not have this, it cannot be used asConstructor。) - Since the arrow function does not have its own
this
, of course it cannot usecall()
,apply()
,bind()
these methods to changethis
the direction.