当前位置:网站首页>Interview ES6
Interview ES6
2022-06-26 07:57:00 【Small slag bright】
Catalog
- Interview es6
- let and const
- Variable structure assignment
- New method of string
- Array extension method
- `... Extension operator `
- `Array.from` It's like an array ( Ergodic ) Of , Convert to a real array
- `Array.of` Convert values to arrays
- `find Find the first array element that meets the criteria 、findIndex Find the index of the first array element that meets the criteria `
- `includes Determine whether an array contains an element , Returns a Boolean value `
- Object extension method
- `Object.is() An absolute judgment of two values `
- `Object.assign() Merge of objects , Expand a new object for the first target object `
- `Object.keys(obj) Get the properties of an object , It can be used to clear the property value of the current object `
- `Object.values(obj2) Traversing objects . Returns an array of ( The current object attribute value is used as each element )`
- ` Chain judgment operator ?. as well as babel The latest transcoding configuration for `
- `Object.assign()`
- Set
Interview es6
let and const
- Use var The variables defined are global variables , That is to say window.XX Variables can be accessed :
- Scope :
- JS In the scope of : Global scope 、 Function scope . There is no concept of block scope .
- ECMAScript 6( abbreviation ES6) New block level scope... In .
- Block scope is defined by { } Include ,if Statement and for In the sentence { } It's also block scoped
Validate block level scope
- because var The defined variables are global variables ,var For a defined variable or function, there is a variable promotion , For simple variable values , Is one step in place , Both the definition value and the assignment value are promoted , Then it will print out b Value ;( Be careful : Variable promotion of function , Just the definition of the lifting function , Do not promote function calls , The message queue needs to be executed according to the , First, execute the synchronization task step by step !)
- because let and const There are block level scopes , There is no such thing as variable escalation , Therefore, access is restricted to the defined block level scope !( Be careful : The inner block level scope can access the outer variables , This involves access to the scope chain )
- let Variables defined , In block level scope , It can only be defined once , If not, it will prompt XX Variable has already been declared It has been defined ( Be careful :let Variables defined , The defined value can be modified )
- const Variables defined , Has block level scope , Can only be defined once within a block level scope , If not, the prompt has been defined , It is worth noting that const The variables defined are read-only , Immutable , If not, it will prompt XXX is read-only
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
};
},
created() {
this.init();
},
methods: {
init() {
{
var b = 10;
let c = 20;
// let c; c has already been declared
const d = 30;
// d = 40; // "d" is read-only
console.log(" Inside b", b, " Inside c", c, " Inside d", d); // Inside b 10 Inside c 20 Inside d 30
{
console.log(" In the second floor c", c); // In the second floor c 20
}
}
console.log(" Outside b", b); // Outside b 10
// console.log(" Outside c", c); // Report errors c is not defined
// console.log(" Outside d", d);// Report errors d is not defined
var aArr = [];
for (var i = 0; i < 5; i++) {
aArr[i] = function () {
console.log(i);
};
}
aArr[4](); // 5
// because var The defined variables are global variables , stay for At the end of the cycle ,i by 5
let bArr = [];
for (let i = 0; i < 5; i++) {
bArr[i] = function () {
console.log(i);
};
}
bArr[4](); // 4 because let The defined variable has a block level scope , Inside the function i Values are not overwritten , Therefore, when retrieving data , The value that has not been overwritten
},
},
};
</script>
Variable structure assignment
The deconstruction of arrays
- Deconstruct according to the corresponding order of the array , If there is a corresponding value , Then the corresponding value is deconstructed , If there is no value , Then the value of deconstruction is
undefined - Arrays can be deconstructed against nested arrays
- Array deconstruction , Default values can be set (** Be careful : Namely ES6 The strict equality operator is used internally (=) Only when the value is undefined when , So that the default value can be realized , however null value ! undefined **)
// The deconstruction of arrays :
let a = [1, 2, 3, [4]];
let b = [];
let [a1, a2, a3, a4] = a;
let [b1, b2] = b;
console.log("a And a1", a1, "a2", a2, "a3", a3, "a4", a4); // a Of the array structure a1 1 a2 2 a3 3 a4 4
console.log("b1", b1, "b1 sentence ", b1 ? b1 : ""); // b1 undefined b1 sentence
console.log("b2", b2, "b2 sentence ", b2 ? b2 : ""); //b2 undefined b2 sentence
let [c, ...d] = [1, 2, 3, 4];
console.log("c", c, "d", d); // c 1 d [2,3,4]
let [x = "aaa", y] = [undefined, null];
console.log("x", x, "y", y); // x aaa y null
Object deconstruction
- Object deconstruction is based on the existing attributes of the object , When there is no corresponding attribute , The value of deconstruction is
undefined - Others are the same as array structures
// Object deconstruction
let {
a, b, c, d: dd, e = "e" }
= {
a: "aaa", b: "bbb", d: "ddd",e:"eee" };
console.log("a", a, "b", b, "c", c, ); // a aaa b bbb c undefined
console.log("dd", dd,"e",e); // dd ddd e eee;
let obj = {
arr: [
"xxx",
{
y: "yyy",
},
],
};
let {
arr: [x, {
y }],
arr: newA,
} = obj;
console.log("x", x, "y", y, "newA", newA); // x xxx y yyy newA ['xxx', {y: "yyy",}]
// Structure of objects
let obj3 = {
x: 1, y: 2, z: 3, w: 4, q: 5 };
let {
x, y, ...ww } = obj3;
console.log("x", x, "y", y, "ww", ww); // x 1 y 2 ww {z: 3, w: 4, q: 5}
New method of string
There are three ways to determine whether a character exists includes startsWith endsWith
- includes: Determine whether the string contains a character , Return value is Boolean
- startsWith: Determine the beginning of a string and whether it contains a character , Return value is Boolean
- endsWith: Determine the end of a string and whether it contains a character , Return value is Boolean
- Be careful : These three methods have two parameters , The first parameter is the value to look for , The second parameter is location ;
- includes And startsWith Second parameter in , It represents from the first n Index (s) to start searching
- endsWith The second parameter in , It represents 0- The first n Search within characters
let str = "www Vegetable chicken www! Vegetable chicken 2!.com!"; // Spaces occupy one character
console.log("includes", str.includes(" food ")); // includes true
console.log("startsWith", str.startsWith("www")); // startsWith true
console.log("endsWith", str.endsWith("!")); // endsWith true
console.log("includes-2", str.includes(" food ", 5)); // includes-2 true
console.log("startsWith-2", str.startsWith("www", 6)); // startsWith-2 true
console.log("endsWith-2", str.endsWith("!", 4)); // endsWith-2 false
console.log("endsWith-2", str.endsWith("!", 10)); // endsWith-2 true
repeat Rewrite the string several times
- effect : Just rewrite a string several times , And finally put it together , Returns the combined value
let str = "xzl";
console.log(" Repeat the string 3 return ", str.repeat(3)); // Repeat the string 3 return xzlxzlxzl
Clear the spaces in the string trim trimStart trimEnd
- trim:ES5 There's a way
- trimStart 、trimEnd: yes ES2019(ES10 Methods )
let str1 = " xzl";
let str2 = " xzl ";
console.log(" Empty 1",str1.trim(""));
console.log(" Empty 2",str1.trimStart(""));
console.log(" Empty 3",str2.trimEnd(""));
// Empty 1 xzl // trim Empty character string The space on the left and right
// Empty 2 xzl // trimStart Empty character string The space on the left
// Empty 3 xzl // trimEnd Empty character string The space on the right
The method of global matching string replaceAll
- replaceAll Is the global matching string , Then replace with the value you want to replace (ES2021)
let str = " xzlxzlxzl";
console.log(" The first match replaces ", str.replace("xzl", " Vegetable chicken "));
// The first match replaces Vegetable chicken xzlxzl
console.log(" Regular global matching ", str.replace(/xzl/g, " residue "));
// Regular global matching Slag slag
// Use es2021
console.log("replaceAll()", str.replaceAll("xzl", " Xiao Liang "));
// replaceAll() Xiao Liang Xiao Liang
Array extension method
... Extension operator
- effect 1: Split the array into strings , Or give the outer layer an array , Expand the current array
- effect 2: You can also use
Math Such methodFind the maximum value of the array , minimum value - effect 3: Shallow copy array , That is to extend the original array with the extension operator , Assign to a new array !( Implement shallow copy of array -> Just for the values stored on the stack , Not for complex data objects ( The stack stores an address , This address points to the values in the heap ))
- effect 4: Split the string into an array
let arr = [1, 2, 3];
console.log(" The extended operator of an array ", ...arr); // The extended operator of an array 1 2 3
console.log(" The extended operator of an array ", [0, ...arr]); // The extended operator of an array [0, 1, 2, 3]
// For maximum
console.log(" The maximum value is :", Math.max(...[14, 3, 77]));// The maximum value is : 77
console.log(" The minimum value is :", Math.min(...[14, 3, 77]));// The minimum value is : 3
// Shallow copy of the array
let list = [
{
name: "xpl", age: 20 },
{
name: "xzl", age: 30 },
];
let newList = [...list];
list[0].name = " modify "
console.log(" The original array list", list);
// [{ name: " modify ", age: 20 },{ name: "xzl", age: 30 }]
console.log(" Deep copy array newList", newList);
// [{ name: " modify ", age: 20 },{ name: "xzl", age: 30 }]
// hold String to array
console.log(" String to array ", ['w', ..."ww"]);// String to array ['w', 'w', 'w']
Array.from It's like an array ( Ergodic ) Of , Convert to a real array
- Array.from Method to convert two types of objects into real arrays : Array like objects (array-like object) Ergodic (iterable) The object of ( Include ES6 New data structure Set and Map)
let obj = {
0: "a",
1: "b",
2: "c",
length: 3
};
console.log(" Convert to array ", Array.from(obj)); // Convert to array ['a', 'b', 'c']
Array.of Convert values to arrays
console.log(" Convert values to arrays ", Array.of(1)); // [1]
console.log(" Convert values to arrays ", Array.of(1, 2, 3)); // [1, 2, 3]
find Find the first array element that meets the criteria 、findIndex Find the index of the first array element that meets the criteria
// find To find the first qualified member of the array , And return the currently found array elements
let arr = [1, 5, 9, -10, 30, 40];
let newVal = arr.find((item) => {
return item > 10;
});
console.log("newVal", newVal); // newVal 30
let arr2 = [{
name: "ppp" }, {
name: "ccc" }];
let newArr = arr2.find((item) => {
return item.name == "ppp";
});
console.log("newArr", newArr); // newArr {name: 'ppp'}
// findIndex To find the first qualified member of the array , And return the index of the currently found array element
let idx = arr.findIndex((item) => {
return item > 10;
});
console.log("idx", idx); // idx 4
includes Determine whether an array contains an element , Returns a Boolean value
// includes Determine whether an array contains an element , Returns a Boolean value
// Parameters : Parameters 1: Value found , Parameters 2: Index started
let arr = [1, 3, 5];
console.log("res", arr.includes(3)); //res true
console.log("res", arr.includes(0)); //res false
console.log("res", arr.includes(3, 2)); //res false
console.log("res", arr.includes(3, 0)); //res true
console.log("res", [NaN].includes(NaN)); // res true
Object extension method
Object.is() An absolute judgment of two values
- 1: Make an absolute judgment on the two values
- 2: Can be correctly distinguished
+0On-0 - 3: Two complex objects cannot be judged , But it can judge whether the values of two complex objects are exactly the same
- 4: in the light of NaN You can also achieve absolute equality
console.log("res1", Object.is("a", "a"));
console.log("res2", Object.is("+0", "-0"));
console.log("res3", Object.is({
}, {
}));
console.log("res4", Object.is({
age: 20 }, {
age: 20 }));
console.log("res5", Object.is(NaN, NaN));
let obj1 = {
age:10}
let obj2 = {
age:10}
console.log("res6", Object.is(obj1.age, obj2.age));
// res1 true
// res2 false
// res3 false
// res4 false
// res5 true
// res6 true
Object.assign() Merge of objects , Expand a new object for the first target object
- 1:Object.assign( tar , obj1 obj2 ... )
- 2: Parameters 1:tar > This is the target object , Objects that need to be extended , For the following object data , Merge them into the current target object !
- 3: Be careful : That is, the target object has the same attribute value as the subsequent object , Then take the attribute value of the subsequent object , As a result !
- 4: If only the target object , Finally, the target object is returned , That is, it does not participate in extending object attributes
- 5: If the parameter is not an object , First convert to an object , Then return the converted object value
Be careful:Object.assign() For light copy , When the attribute value of the target object changes , This will affect the result of the current merged object
let targetObj = {
a: 1, b: 1 };
const obj1 = {
b: 2 };
const obj2 = {
c: 3 };
let res1 = Object.assign(targetObj, obj1, obj2);
console.log("res1", res1); // res1 {a: 1, b: 2, c: 3}
let res2 = Object.assign("11");
console.log("res2", res2); // res2 String {'11'}
Object.keys(obj) Get the properties of an object , It can be used to clear the property value of the current object
- Traverse the current object , Get the properties of the current object
- Return results : An array ( An element consisting of the attribute values of the current object )
let obj = {
name: "ppp",
age: 20,
sex: " male ",
};
// Traversing objects Gets the property value of the object
Object.keys(obj).forEach((item) => {
console.log("item", item);
obj[item] = "";
});
// item name
// item age
// item sex
console.log("obj", obj); // {name: '', age: '', sex: ''} Traversing objects , Clear the property value of the current object !
console.log("res2", Object.keys(obj)); // ['name', 'age', 'sex']
Object.values(obj2) Traversing objects . Returns an array of ( The current object attribute value is used as each element )
let obj2 = {
name: "ppp2",
age: 202,
sex: " male 2",
address: "",
};
// Traversing objects Gets the property value of the object Returns an array of attribute values
console.log("arr", Object.values(obj2)); // arr ['ppp2', 202, ' male 2', '']
Chain judgment operator ?. as well as babel The latest transcoding configuration for
- Read an attribute of an object , You need to determine whether the current attribute exists , It takes another step to judge , But with
Chain judgment operator ?. It will save a lot - install :
yarn add @babel/preset-env --dev - .babelrc
.babelrc
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry"
}
]
]
}
Use
// es2020 Link evaluator
let obj1 = {
a: 10,
b: {
body: {
user: "xzl",
},
},
};
let res = obj1?.b?.body?.user;
console.log(" Link evaluator ", res);// Link evaluator xzl
Object.assign()
Set
Set aggregate
- characteristic :
It's like an array , But the values of the members are unique , There are no duplicate values - effect 1: It can be used for de duplication of values of simple data types ( In the array )、 The same principle can also be used for string de duplication
// Set It's like an array , But the values of the members are unique , There are no duplicate values
let arr = [1, 1, 22, 2, 3, 3, 1, 7];
console.log("res", new Set(arr), "arr", [...new Set(arr)]);
// res {1, 22, 2, 3, 7} arr [1, 22, 2, 3, 7]
// Be careful :Set Only for simple data types stored on the stack that have no duplicate values , But the object is not covered !
let arr2 = [{
name: "ppp" }, {
name: "ppp" }];
console.log("arr2", new Set(arr2)); // arr2 [{ name: "ppp" }, { name: "ppp" }];
// Can be used for string de duplication
let str = "aabbccds";
let res3 = [...new Set(str)].join("");
console.log("res3",res3);// res3 abcds
边栏推荐
- Encapsulating ranging and surface class based on leaflet
- Median segmentation (find rules) - Niuke
- Uni app is similar to Taobao in selecting multiple specifications of commodities (inventory judgment)
- My colleague asked a question I never thought about. Why did kubernetes' superfluous' launch the static pod concept?
- Quickly upload data sets and other files to Google colab ------ solve the problem of slow uploading colab files
- Automatic backup of MySQL database in the early morning with Linux
- 手机开户哪个证券公司佣金最低?网上开户是否安全么?
- Web technology sharing | webrtc recording video stream
- Opencv mouse event + interface interaction drawing rectangle polygon selection ROI
- Common uniapp configurations
猜你喜欢

Web technology sharing | webrtc recording video stream
![Jemter stress test - visualization tool - [usage]](/img/b1/3c367b690bbc16ae5a3e9e2c85af73.png)
Jemter stress test - visualization tool - [usage]

Cloud native integration data warehouse heavy release

数据中心灾难恢复的重要参考指标:RTO和RPO

OSPF design principles, commands take H3C as an example

Ping An technology's practice of migrating from Oracle to ubisql

buuresevewp

Data governance: from top project to data culture!

I want to create SQL data (storage structure)

Livevideostackcon | evolution of streaming media distribution for online education business
随机推荐
Detailed explanation and code implementation of soft voting and hard voting mechanism in integrated learning
What is the five levels of cultivation of MES management system
Deeply analyze storage costs and find cost reduction solutions
Use intent to shuttle between activities -- use implicit intent
[SystemVerilog basics] post_ Randomize function record
PyTorch-12 GAN、WGAN
Junit
Here is the command to display the disk space usage. Go ahead and pay attention to more wonderful things!
Uniapp uses uviewui
[industry cloud talk live room] tomorrow afternoon! Focus on digital intelligence transformation of the park
CMDA 3634 image processing
Web technology sharing | webrtc recording video stream
Google Earth Engine(GEE) 01-中输入提示快捷键Ctrl+space无法使用的问题
Test method - decision table learning
The first screen time, you said you optimized it, then you calculated it and showed it to me!
I want to create SQL data (storage structure)
Google Earth engine (GEE) 01- the prompt shortcut ctrl+space cannot be used
1002: easy to remember phone number
我想要股票账户优惠开户,如何操作?手机开户安全么?
信息学奥赛一本通 1354:括弧匹配检验