当前位置:网站首页>New methods and features of ES6 built-in objects
New methods and features of ES6 built-in objects
2022-07-28 05:16:00 【M78_ Domestic 007】
One 、Map And Set
Map
Map Object to save key value pairs , Any value can be a key or a value , And contrast with object, Its key can only be string or symbols.
Map characteristic : Orderly 、 Key value pair ( The key can be any type )、 The key name cannot be repeated ( If repeat , So cover )
Usage method :
1、new Map(), Get one Map object
2、Map Of set Methods Map Object to set key value pairs , Such as mymap.set("a"," I am a ")
3、Map Of get Method obtains the value through the key value , Such as :mymap.get("a")
4、Map Of delete Method to delete a value , Such as :mymap.delete("key");
5、Map Of clear Method to clear the value ;
6、Map.size obtain Map Length of object .
Add :Map There are also entries Method returns a new one Iterator object , It contains... In insertion order Map Of each element in the object [key, value] Array ;
keys Method returns a new one Iterator object , It contains... In insertion order Map The key of each element in the object ;
values Method returns a new one Iterator object , It contains... In insertion order Map The value of each element in the object .
Map The object is an iteratable object , Can pass ES6 New syntax to traverse it .
Code display :
<script>
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
console.log(key + " = " + value);
// Print :0=zero 1=one
}
</script>Map Operations on objects
Map And Array Transformation
Map The constructor can convert a two-dimensional array of key value pairs into a Map object , Use Array.from Function can Map Object to an array of two-dimensional key value pairs
Map The clone
Code demonstration :
<script>
var arr=[[1,10],[2,90],["hello",100]]
var m1=new Map(arr)
var m2=new Map(m1);
</script>Pay attention to is m1!==m2, Because they are two objects .
Map The merger of
<script>
var first = new Map([[1, 'one'], [2, 'two'], [3, 'three']]);
var second = new Map([[1, 'uno'], [2, 'dos']]);
// Merge two Map Object time , If there are duplicate key values , Then the latter will cover the former , The corresponding value is uno,dos, three
var merged = new Map([...first, ...second]);
</script>Set
Set Object allows you to store unique values of any type , Whether it's the original value or the object reference , And Map The difference is that it does not store key value pairs , At the same time, it is disordered .
The only value :Set There is no duplicate value for the value in the object , Note that although two NaN It's not equal , But in Set It cannot be repeated in .
Set Operations on objects
adopt Set Object's add Method to add elements to the object , Such as myset.add(1)
Type conversion
An array with the Set Transformation
<script>
// Array rotation Set
var myset=new Set([1,"a",2,"b"])
//Set Turn array
var myArray=[...myset]
</script>String and Set Transformation
<script>
// String rotation Set
var myset=new Set("hello")
console.log(mySet);// Set(4) {"h", "e", "l", "o"}
// Because convert to Set Object will not have duplicate values , So there's a l Deleted
// notes :Set in toString The way is not to Set convert to String
</script>intersection 、 Combine 、 Subtraction operation
<script>
var a = new Set([1, 2, 3]);
var b = new Set([4, 3, 2]);
// Combine
var union = new Set([...a, ...b]); // {1, 2, 3, 4}
// intersection
var intersect = new Set([...a].filter(x => b.has(x))); // {2, 3}
// Difference set
var difference = new Set([...a].filter(x => !b.has(x))); // {1}
</script>Set Object is used most in the actual development to remove the duplication of the array .
Two 、 String related methods
String recognition :
1、includes() Returns a Boolean value , Determine if the parameter string is found .
2、startsWith() Returns a Boolean value , Judge whether the parameter string is in the head of the original string .
3、endWith() Returns a Boolean value , Judge whether the parameter string is at the end of the original string .
Be careful :
These three methods only return Boolean values , If you need to know the position of the substring , Still have to use indexOf and lastIndexOf .
If these three methods pass in a regular expression instead of a string , Will throw an error . and indexOf and lastIndexOf These two methods , They convert the regular expression to a string and search for it .
Duplicate string :
1、repeat(" Parameters ") Returns a new string , Indicates that the string is repeated a specified number of times .
Note that if the parameter is decimal, round it down , If it is a string, convert it to a number before , If the parameter is negative or infinity False report , If it is NaN Is equal to zero times
String completion :
1、padStart: Returns a new string , Indicates that the parameter string is used to complete the original string from the header .
2、padEnd: Returns a new string , Indicates that the parameter string is used to complete the original string from the tail .
The above two methods accept two parameters , The first parameter is to specify the minimum length of the generated string , The second parameter is the string used to complete . If the second parameter is not specified , Fill with space by default .
Code display :
<script>
console.log("ello".padStart(5,"h")); // "hello"
console.log("hell".padEnd(5,"o")); // "hello"
console.log("h".padStart(5)); // " h"
console.log("h".padEnd(5)); //"h "
</script>If the specified length is less than or equal to the length of the original string , Return the original string ;
If the length of the original string plus the completion string is greater than the specified length , Then cut out the exceeding digits .
Template string :
The template string is equivalent to the enhanced version of the string , Use back quotes `, Focus on adding variables and expressions to strings .
Line breaks and spaces will be preserved
Illustrate with examples :
<script>
// Put variables in ${} Can be added to the string
let info = `My Name is ${name},I am ${age+1} years old next year.`
// You can also call functions in strings
function fn(){
console.log(" You called me ")
}
var re=`my function${fn()}`
</script>3、 ... and 、 Numerical correlation method
Added a method to check whether a number is limited Number.isFinite()
Be careful :Number.isFinate There is no implicit Number() Type conversion , All non numeric values return false
improvement isNaN,Number.isNaN() No implicit number() Type conversion , Not NaN return false; and isNaN() Not NaN return true
Four 、Math Object related extensions :
Math.cbrt(): Used to calculate the cube root of a number .
Math.imul(): Two numbers 32 The result of multiplication in the form of signed integers , It's also a 32 Signed integer with bit .
Math.hypot(): Used to calculate the square root of the sum of squares of all parameters . Pythagorean theorem
Four 、 Object related :
Object literal :
ES6 Allow object attributes to write variables directly , In this case, the attribute name is the variable name , Attribute values are variable values .
In the object , Method names can also be abbreviated :
<script>
const age = 12;
var obj={
age,
fun(){
//....
}
}
</script>ES6 It is also allowed to use expressions as attribute names , But be sure to put the expression in square brackets .
for example :
<script>
var obj={
["f"+"un"](){
//....
}
}
</script>Be careful : The concise representation of an attribute and the expression of an attribute name cannot be used at the same time , Otherwise, an error will be reported .
Add a new expansion operator (...) Used to extract all traversable properties of the parameter object and copy it to the current object . Often used to merge two objects .
demonstration :
<script>
let person = {name: "Amy", age: 15};
let someone = {name: "Mike", age: 17, ...person};
console.log(someone); //{name: "Amy", age: 15}
</script>When the custom attributes are the same as those in the extended operator object , Just overwrite the previous value with the latter value .
Illustrate with examples :
<script>
let person = {name: "Amy", age: 15};
let someone = { ...person, name: "Mike", age: 17};
console.log(someone); //{name: "Mike", age: 17}
let person = {name: "Amy", age: 15};
let someone = {name: "Mike", age: 17, ...person};
console.log(someone); //{name: "Amy", age: 15}
</script>New methods of object :
Object.is(value1, value2): Used to compare whether two values are strictly equal , And (===) similar .
But it's connected to === There is a difference ,object.is(+0,-0) return false,object.is(NaN,NaN) return true
5、 ... and 、 Array correlation
Provides a new way to create arrays :
1、Array.of(): Form an array of all the values in the parameter as elements . Such as :Array.of(1,2,3,4), When the parameter in brackets is empty , Create an empty array .
2、Array.from(arrayLike,[ mapFn,[thisArg]] ): Converts a class array object or iteratable object to an array . The front will Map This method is used to convert iteratable objects into arrays , It is worth noting that when the parameter bits contain empty bits , The corresponding position in the array returns undefined.
Parameter description :arrayLike The class array object or iteratable object you want to convert ;
mapFn: Optional ,map function , Used to process each element , Into the array are the processed elements .
thisArg: Optional , Is used to specify the map Function execution time this object
<script>
let s=new Set([1,2,3,4,4,4])
var re=Array.from(s,function(e){
console.log(e,this)
//2 []
//4 []
//6 []
//8 []
return e*2 // Processing of each element in the array
},[])// Appoint this Point to this []
</script>Class array object : A class array object must contain length attribute , And the element attribute name must be a numeric value or a character that can be converted to a numeric value .
Example
<script>
// An array of class
let obj = {
0: '1',
1: '2',
2: 3,
length: 3
}
</script>New method :
1、find(): Find the elements in the array that match the criteria , If there are more than one element that meets the criteria , Then return the first element .
<script>
let arr = Array.of(1, 2, 3, 4);
console.log(arr.find(item => item > 2)); // 3
</script>2、 findIndex(): Find the index of the eligible elements in the array , If there are more than one element that meets the criteria , Returns the first element index , And find The method is similar .
3、fill(): Fills the contents of array elements with a range of indexes into a single specified value .
<script>
let arr = Array.of(1, 2, 3, 4);
// Parameters 1: The value to fill
// Parameters 2: The starting index to be filled
// Parameters 3( Optional ): Filled end index , The default is the end of the array
console.log(arr.fill(0,1,2)); // [1, 0, 3, 4]
</script>4、 entrys(): Traversal key value pairs
5、keys(): Traverse the key name
6、values(): Traverse the key values
7、includes(): Whether the array contains the specified value . Be careful : And Set and Map Of has Method of differentiation ;Set Of has Method is used to find the value ;Map Of has Method is used to find the key name .
8、flat(): Nested array to one-dimensional array
<script>
console.log([1 ,[2, 3]].flat()); // [1, 2, 3]
</script>边栏推荐
- 类和对象【中】
- 这种动态规划你见过吗——状态机动态规划之股票问题(中)
- C language classic 100 question exercise (1~21)
- 【SLAM】LVI-SAM解析——综述
- php7.1 连接sqlserver2008r2 如何测试成功
- How to quickly turn function test to automatic test
- Driving the powerful functions of EVM and xcm, how subwallet enables Boca and moonbeam
- CPU and memory usage are too high. How to modify RTSP round robin detection parameters to reduce server consumption?
- Interpreting the source code of cfrunloopref
- Evolution of ape counseling technology: helping teaching and learning conceive future schools
猜你喜欢

What tools do software testers need to know?

【CPU占用高】software_reporter_tool.exe

Evolution of ape counseling technology: helping teaching and learning conceive future schools

Win10 machine learning environment construction pycharm, anaconda, pytorch

MySQL date and time function, varchar and date are mutually converted

Check box error

From the basic concept of micro services to core components - explain and analyze through an example

What should testers know about login security?

Simulink automatically generates STM32 code details

【内功心法】——函数栈帧的创建和销毁(C实现)
随机推荐
HDU 3592 World Exhibition (differential constraint)
[paper notes] - low illumination image enhancement - zeroshot - rrdnet Network - 2020-icme
Dcgan:deep volume general adaptive networks -- paper analysis
数据安全逐步落地,必须紧盯泄露源头
HDU 1914 the stable marriage problem
MySQL 默认隔离级别是RR,为什么阿里等大厂会改成RC?
Improving the readability of UI layer test with puppeter
Online sql to XML tool
The default isolation level of MySQL is RR. Why does Alibaba and other large manufacturers change to RC?
Pipe /createpipe
11.< tag-动态规划和子序列, 子数组>lt.115. 不同的子序列 + lt. 583. 两个字符串的删除操作 dbc
【ARXIV2204】Vision Transformers for Single Image Dehazing
Offline loading of wkwebview and problems encountered
【CVPR2022 oral】Balanced Multimodal Learning via On-the-fly Gradient Modulation
塑料可以执行GB/T 2408 -燃烧性能的测定吗
HDU 3585 maximum shortest distance
From the basic concept of micro services to core components - explain and analyze through an example
C language classic 100 question exercise (1~21)
Win10 machine learning environment construction pycharm, anaconda, pytorch
Array or object, date operation