当前位置:网站首页>Extended operator
Extended operator
2022-07-28 13:16:00 【Pig Xiaoyong】
1. meaning
1. Convert an array to a comma separated sequence of parameters .
Be careful , Only when a function is called , Only extension operators can be placed in parentheses , Otherwise, an error will be reported .
console.log(...[1, 2, 3])
// 1 2 3
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]
2. This operator is mainly used for Function call . This operator takes an array , Change to parameter sequence .
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
add(...numbers) // 42
2. Substitution function apply() Method
apply() Detailed explanation
effect :apply( ) Method calls a given this The value of the function , And as an array ( Or something like an array object ) Provided parameters .
Parameters : Altogether 2 Parameters , All are optional parameters
The first parameter :
this Point to .(this It may not be the actual value seen by this method : If the function is in non-strict mode , Is specified as null or undefined Will be automatically replaced by pointing to the global object , The original value is wrapped .)
The second parameter :
An array or class array object .( The array elements will be passed as separate parameters to the func function . If the value of this parameter is null or undefined, No parameters need to be passed in .)
If no parameters are passed : Then it's a global variable
Because extension operators can expand arrays , So you don't need it anymore apply() Method converts an array into a parameter of a function .
// ES5 Writing
Math.max.apply(null, [14, 3, 77])
// ES6 Writing
Math.max(...[14, 3, 77])
// Equate to
Math.max(14, 3, 77);
// ES5 Writing
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
// ES6 Writing
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
// ES5
new (Date.bind.apply(Date, [null, 2015, 1, 1]))
// ES6
new Date(...[2015, 1, 1]);
3. Application of extension operators
(1) Copy the array
Arrays are composite data types , If you copy directly , Just copied the pointer to the underlying data structure , Instead of cloning a whole new array .
Arrays are composite data types , If you copy directly , Just copied the pointer to the underlying data structure , Instead of cloning a whole new array .
const a1 = [1, 2];
const a2 = a1;
a2[0] = 2;
a1 // [2, 2]
In the above code ,a2 Not at all a1 The clone , It's another pointer to the same data . modify a2, Will lead directly to a1 The change of .
ES5 You can only copy arrays in a flexible way .
const a1 = [1, 2];
const a2 = a1.concat();
a2[0] = 2;
a1 // [1, 2]
In the above code ,a1 Will return a clone of the original array , Revise a2 It won't be right a1 An impact .
Extended operators provide a simple way to copy arrays .
const a1 = [1, 2];
// Writing a
const a2 = [...a1];
// Write two
const [...a2] = a1;
The above two ways of writing ,a2 All are a1 The clone .
(2) Merge array
// ES5 The merge array of
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 The merge array of
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
however , Both methods are shallow copies , You need to pay attention to .
const a1 = [{
foo: 1 }];
const a2 = [{
bar: 2 }];
const a3 = a1.concat(a2);
const a4 = [...a1, ...a2];
a3[0] === a1[0] // true
a4[0] === a1[0] // true
In the above code ,a3 and a4 It's a new array formed by combining two different methods , But their members are all references to the original array members , This is a shallow copy . If you modify the value pointed to by the reference , It will be synchronized to the new array .
(3) Combined with deconstruction assignment
Extension operators can be combined with deconstruction assignments , Used to generate arrays .
// ES5
a = list[0], rest = list.slice(1)
// ES6
[a, ...rest] = list
If the extended operator is used for array assignment , It can only be placed in the last bit of the parameter , Otherwise, an error will be reported .
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
(4) character string
Extension operators can also turn strings into real arrays .
[...'hello']
// [ "h", "e", "l", "l", "o" ]
Capable of correctly recognizing four bytes Unicode character .
JavaScript Four bytes of Unicode character , Identified as 2 Characters , There is no such problem with extension operators . therefore , Functions that correctly return the length of a string , You can write like this .
'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3
function length(str) {
return [...str].length;
}
length('x\uD83D\uDE80y') // 3
(5) Realized Iterator Object of the interface
边栏推荐
- Summary: idea problem record
- 企业数字化本质
- Android engineers, how to use kotlin to provide productivity?
- 【嵌入式C基础】第3篇:常量和变量
- Black cat takes you to learn EMMC Protocol Part 26: hardware reset operation of EMMC (h/w reset)
- Black cat takes you to learn EMMC Protocol Part 24: detailed explanation of EMMC bus test program (cmd19 & cmd14)
- Risk analysis of option trading
- Change password, confirm password verification antd
- LeetCode每日一题(2196. Create Binary Tree From Descriptions)
- The essence of enterprise Digitalization
猜你喜欢

Fundamentals of machine learning Bayesian analysis-14

Machine learning practice - neural network-21

FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be depreca

PCP parity principle arbitrage

Kotlin是如何帮助你避免内存泄漏的?

管理区解耦架构见过吗?能帮客户搞定大难题的

Black cat takes you to learn EMMC Protocol Part 26: hardware reset operation of EMMC (h/w reset)

Smart touch screen LCD bathroom mirror light touch chip-dlt8t02s-jericho

SQL most commonly used basic operation syntax

How to design a second kill system?
随机推荐
Led aquarium lamp touch chip-dlt8t02s-jericho
With 433 remote control UV lamp touch chip-dlt8sa20a-jericho
什么是事务及数据库的优化方法
我抄底了被清算的NFT,却被OpenSea上了锁
[embedded C foundation] Part 6: super detailed explanation of common input and output functions
What if the right button of win11 start menu doesn't respond
Black Scholes Merton European option pricing formula
Transaction of MySQL underlying principle (2)
黑猫带你学eMMC协议第26篇:eMMC的硬件复位操作(H/W reset)
A brief introduction to the for loop. Some of the code involves arrays
Intrinsic value and time value of options
Full disclosure! Huawei cloud distributed cloud native technology and Practice
What if the win11 folder cannot be opened
[July 5 event preview] Flink Summit
STM32 Development Notes - experience sharing
Protective bearish strategy
How to view win11 system and reserved space?
管理区解耦架构见过吗?能帮客户搞定大难题的
【嵌入式C基础】第9篇:C语言指针的基本用法
Use and source code of livedata in jetpack family bucket