[ES6] Ruan Yifeng ES6 learning (2) template strings, new string methods, function extensions, rest parameters, arrow functions

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 indexOfmethods that can be used to determine whether a string is contained within another string. ES6 provides three new methods.

  1. 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, endsWiththe behavior is different from the other two methods. It works on the first ncharacter, while the other two methods work from the first nposition until the end of the string.

  1. repeat()

    repeatThe method returns a new string, which means repeating the original string n.

'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 repeatthe argument is a string, it will be converted to a number first.

'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"
  1. 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'
  1. 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"
  1. 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

BigIntIt 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 Numberdistinguish it from the type, BigIntthe 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

typeofThe operator BigIntreturns for data of type bigint.

typeof 123n // 'bigint'

function extension

  1. 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 letor constdeclared 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 argumentsobjects do not need to be used. restThe 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 argumenta parameter, and argumentsthe object is not an array, but an array-like object. So in order to use the array method, Array.fromit must be converted to an array first. restThere is no such problem with parameters, it is a real array, and all methods unique to arrays can be used.

pushThe 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 restthere 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

  1. 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);

restParameters 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:

  1. Arrow functions do not have their own thisobjects. (For ordinary functions, the internal thispoints to the object where the function is running, but this is not true for the arrow function. It does not have its own thisobject, and the internal one thisis defined in the upper scope this. That is to say, the internal arrow function thisThe pointing is fixed, by contrast, thisthe pointing of ordinary functions is mutable.)
  2. Cannot be used as a constructor, that is, you cannot use newcommands 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。)
  3. Since the arrow function does not have its own this, of course it cannot use call(), apply(), bind()these methods to change thisthe direction.

Guess you like

Origin blog.csdn.net/Bon_nenul/article/details/128189891