当前位置:网站首页>Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
2022-07-28 13:43:00 【Brave * Niuniu】
Strict mode ——let and const—— Arrow function —— Deconstruct assignment —— String templates and symbol——Set and Map—— Generator function
🧡 Strict mode
Variables in strict mode You can't Assignment is called directly without definition
Don't allow Parameter with the same name
prohibit Usewith
Don't Useeval
Don't allow Usearguments.callee
Don't toevalandargumentsassignment
In strict mode Function and callback functionthisPoint toundefined
Read-only property You can't assignment
Can't delete must not Deleted property
8 Base number No longer used in strict mode
<script type="module"> "use strict"; //………………………………………… </script>
<script type="module"> // Auto strict mode </script>
var div=document.querySelector("div");
//div.style.width="30px";
//div.style.height="30px";
//div.style.backgroundColor="red";
// No use with
with(div.style){
width="30px";
height="30px";
backgroundColor="red";
}
var obj={
option:{
a:1,
b:2
}
}
with(obj.option){
a=10;
b=20;
c=30;// If the original attribute of the object exists , Then modify the value of the attribute , Otherwise, a global variable will be redefined
}
console.log(obj,c)
Not allowed
arguments.callee
arguments.callee.caller
console.log(this)//Window
function fn(){
// In functions and callback functions in strict mode this Point to undefined
console.log(this);//undefined
}
fn();
var a=3;
function fn(a){
console.log(a+window.a);//8
}
fn(5);
*eval Reflection Reflect a string as an expression ( Because it is too powerful )ヾ(≧▽≦)o
// Do not use eval
//eval Reflection Reflect a string as an expression
console.log(eval("3+4"));//7
var a=3;
console.log(eval("a+5"));//8
var o1={
},o2={
},o3={
};
for(var i=1;i<4;i++){
eval("o"+i).a=10;
}
console.log(o1,o2,o3)//{a: 10} {a: 10} {a: 10}
🧡let and const
Defining variables
let a=1;
Define constants
const b=3;
Personal explanation ;
var Like a global variable
letWith{}Limit the scope , And it cannot be reused in the same scope let Define the same variable nameconstConstant Is the value that cannot be changed after definition
Generally speaking, constants must be capitalized , Moreover, with _ Distinguish words
var a=3;
{
a=4;
}
console.log(a);//4
let a=3;
{
a=5;
}
console.log(a)//8
In block statements let The defined variables are variables within the scope of the block , Not callable outside the block
let a=3;
{
let a=5;// In block statements let The defined variables are variables within the scope of the block , Not callable outside the block
}
console.log(a);//3
for(var i=0;i<10;i++){
}
console.log(i)//10
and
for(let i=0;i<10;i++){
}
console.log(i)// Report errors
const obj={
a:1,b:2};
obj={
a:3,b:3};// To prevent a reference type from changing its reference address
obj.a=10;// You can change its value , But its reference address cannot be modified
obj=null;
Don't write like this
Arrow function
* The arrow function actually defines an anonymous function
* If there is only one parameter in the arrow function , It can be omitted ()
* If there are no parameters in the arrow function , Or more than one parameter , You have to use ()
If there is only one statement in the function , It can be omitted {}
* At the same time, it is equivalent to adding return Return the result of this expression
Arrow statements are used to handle this Point to The problem ofthisPoint to specific click here this Point to Daquan
var fn=(a,b)=>{
return a+b;
}
Equivalent to
var fn=function(a,b){
return a+b;
}
// If there is only one parameter in the arrow function , It can be omitted ()
// If there are no parameters in the arrow function , Or more than one parameter , You have to use ()
var fn=(a)=>{
console.log(a);//3
}
var fn=a=>{
console.log(a);//3
}
fn(3);
var fn=(a,b)=>{
return a+b;
}
If there is only one statement in the function , It can be omitted {
}
At the same time, it is equivalent to adding return Return the result of this expression
var fn=(a,b)=>a+b;
var obj={
c:this.d, Outside the current object this Point to
a(){
console.log(this);obj
},
b:()=>{
console.log(this);// Point outside the current arrow function this Point to , and c Property assignment this.d Point to this identical
}
}
obj.a();
obj.b();
"use strict";
var obj={
a(){
console.log(this);//obj
// function fn(){
// console.log(this);// All functions call directly ,this All point to window, Strict mode points to undefined
// }
// fn();
var fn=()=>{
console.log(this);//this Pointing to the context outside the arrow function this,obj
}
fn();{
a: ƒ}
}
}
obj.a();
var obj={
ab:10,
a(){
console.log(this);//obj
// there this Namely obj
// take obj Assign a value to document.o attribute
document.o=this;
document.addEventListener("click",this.clickHandler);
},
clickHandler(e){
// Who listens this Who is the
console.log(this)//document
// Because it is assigned to the reference address , So the following two statements are the same
console.log(this.o.ab);//10
console.log(obj.ab);//10
}
};
obj.a()
The traditional event function this Point to the listening element
document.addEventListener('click',function(){
console.log(this);//#doucument
})
Arrow function this Turn out , And call outside the function this Equivalent
document.addEventListener("click",e=>{
console.log(this);//obj
})
var obj={
ab:10,
a(){
this.handler=e=>this.b(e);
document.addEventListener("click",this.handler);
},
b(e){
e.currentTarget.removeEventListener("click",this.handler);
console.log(this.ab);
}
}
var o=obj;
obj={
};
o.a();
Deconstruct assignment
An array of deconstruction
Bitwise deconstruction
ES5 Default values are not allowed in parameter
ES6 You can set default values for parameters
var arr=[1,2,3];
var [a,b,c]=arr;
console.log(a,b,c);//1 2 3
var obj={
a:1,b:3,c:4};
var {
a,b,c}=obj;
console.log(a,b,c);//1 3 4
Exchange of variables
var a=3;
var b=4;
[a,b]=[b,a];
console.log(a,b)//4 3
3 No assignment
var [a,b]=[1,2,3];
console.log(a,b);//1 2
c yes undefined
var [a,b,c]=[1,2];
console.log(a,b,c);//1 2 undefined
If the array deconstruction is not assigned to c,c The default value is 3
var [a,b,c=3]=[1,2];
console.log(a,b,c);//1 2 3
Object deconstruction
Variables and key Corresponding deconstruction , The variable name must be the same as key Same value
Object deconstruction is independent of order
When an object is deeply deconstructed , Properties with the same name , Alias is needed when deconstructing
var {
a,b,c}={
b:10,a:3,c:6};
console.log(a,b,c)//3 10 6
function fn(a,b=2,c){
console.log(a,b,c);//3 2 5
}
fn(3,undefined,5);
function fn({
a,b,c}){
console.log(a,c,b);//10 20 undefined
}
fn({
a:10,c:20});
var {
a,b,c=3}={
a:1,b:2};
console.log(a,b,c);//1 2 3
var {
a,b:{
a:a1}}={
a:1,b:{
a:2}};
console.log(a,a1);//1 2
All object methods with instances should not be deconstructed
Some objects use this, This object cannot be deconstructed , If after deconstruction ,this The direction of will change
var str="abvcde";
var {
length:len}=str;
console.log(len);//6
These two belong to deconstructible
var {
random,max}=Math;
console.log(random()*10)
console.log(max(10,20))
Deconstruction exercise
var {
a,b:{
a:a1=3}={
a:10}}={
a:1,b:{
a:2}}
a=1 a1=2
var {
a,b:{
a:a1=3}={
a:10}}={
a:1}
a=1 a1=10
var {
a,b:{
a:a1=3}={
a:10}}={
a:1,b:{
}};
a=1 a1=3
function fn({
a,b:{
a:a1}={
a:10}}={
a:20,b:{
a:30}}){
console.log(a,a1);
}
fn();//20,30
fn({
});//undefined 10
fn({
a:1});//1 10
fn({
a:1,b:{
}});//1 undefined
fn({
a:1,b:{
a:50}});//1 50
var obj= {
a:10,b:{
b:{
a:20}}};
a=10 a1=20;
var obj={
a:10,b:{
b:{
}}};
a=10 a1=100
var obj={
b:{
}}
a=20 a1=0;
var obj={
};
a=20 a1=-1
var {
a=20,b:{
b:{
a:a1=100}={
a:0}}={
b:{
a:-1}}}=obj;
console.log(a,a1)
String templates and symbol
“``” interpolation
symbol No repetition , The only type
Symbol No arithmetic
In the object key You can use character type and Symbol type
Use Symbol As key Can prevent key Because of duplicate names
var div=document.querySelector("div");
var list=[
{
site:" tencent ",href:"http://www.tencent.com"},
{
site:" Baidu ",href:"http://www.baidu.com"},
{
site:" JD.COM ",href:"http://www.jd.com"},
{
site:" TaoBao ",href:"http://www.taobao.com"},
{
site:" NetEase ",href:"http://www.163.com"},
{
site:" millet ",href:"http://www.mi.com"}
]
div.innerHTML=` <ul> ${
list.reduce((v,t)=>`${
v}<li><a href='${
t.href}'>${
t.site}</a></li>`,"")} </ul> `
div.innerHTML=` <ul> ${
(function(){
var str=""; for(let i=0;i<list.length;i++){
str+=`<li><a href='${
list[i].href}'>${
list[i].site}</a></li>` } return str; })()} </ul> `
var a=Symbol();
var b=Symbol();
var obj={
[a]:10,
[b]:20
}
console.log(obj[a]);
Be able to use for in key Is a string type attribute , instead of Symbol type
for(var key in obj){
console.log(key)
}
Remove Magic strings
const LEFT=Symbol(),TOP=Symbol(),RIGHT=Symbol(),BOTTOM=Symbol();
var list = [LEFT,TOP,RIGHT,BOTTOM];
var state;
init();
function init() {
document.addEventListener("keydown", keyHandler);
document.addEventListener("keyup", keyHandler);
setInterval(animation, 16);
}
function keyHandler(e) {
if(e.type==="keyup") return state=undefined;
state = list[e.keyCode - 37];
state=TOP;
}
function animation() {
if (!state) return;
switch (state) {
case LEFT:
console.log("left")
break;
case TOP:
console.log("top")
break;
case RIGHT:
console.log("right")
break;
case BOTTOM:
console.log("bottom")
break;
}
}
Set and Map
Array List of elements
The element does not point to a name , With subscript , Tight structure , According to the previous one, you can find the latter , There is context, so it can be sorted , Adding and deleting elements is slow , The elements of the array can be repeated , Traversal lookup required
Object Key value pair
disorder , Loose structure , There is no context , Fast insertion speed , Delete fast , Fast search speed ( With key Storage )
Set
No index , unordered set , There is no context , Insert , Delete fast , Can't sort , Can't repeat . Set has quantity length size
Map
var m=new Map([[“a”,1],[“b”,2]]);
var m=new Map( iterator )
| Key value pair | attribute key | length | structure | The order |
|---|---|---|---|---|
| object | string、Symbol | No, | Loose structure | First value After character key, countless Symbol |
| Map | Any type | Yes size | Loose structure | lack order ( Traverse in the order of addition ) |
var m=new Map([["a",1],["b",2]]);
console.log(m)
//Map(2) {'a' => 1, 'b' => 2}
// var m=new Map( iterator )
var o={
a:1,b:2,c:3};
console.dir(Object);//Object()
// The array structure required to convert an object to an iterator
var arr=Object.entries(o);
console.log(arr)//[Array(2), Array(2), Array(2)]
// take o The object is put into map, Convert to map
var m=new Map(Object.entries(o));
console.log(m);//Map(3) {'a' => 1, 'b' => 2, 'c' => 3}
// Put the iterator map Convert to object
var o1=Object.fromEntries(m);
console.log(o1)//{a: 1, b: 2, c: 3}
| Empty | according to key Get value | Delete the value according to the key | Determine whether there is this key value pair | Get the number of key value pairs |
|---|---|---|---|---|
| m.clear() | m.get(“a”) | m.delete(‘true’); | m.has(“true”) | m.size |
| delete Delete object |
Traverse map:
var m=new Map();
m.set("a",1);
m.set(true,2);
m.set("true",0);
var o={
a:1};
m.set(o,3);// Use the reference address of the object as the key storage
var o1=o;
o={
a:3};
m.forEach(function(value,key){
console.log(key,value)
})
for(var [key,value] of m){
console.log(key,value)
}
// m.keys() obtain map Of key The corresponding iterator
// m.values() obtain map Of value The corresponding iterator
// Only traverse all key
for(var key of m.keys()){
console.log(key);
}
for(var value of m.values()){
console.log(value)
}
for(var [key,value] of m.entries()){
console.log(key,value)
}
Sequential clicker 
var m=new Map();
var bns=document.querySelectorAll("button");
m.set(bns[0],bns[1]);
m.set(bns[1],bns[2]);
m.set(bns[2],bns[3]);
m.set(bns[3],bns[4]);
bns[0].addEventListener("click",clickHandler);
function clickHandler(e){
console.log(this.textContent);
this.removeEventListener("click",clickHandler);
if(!m.has(this)) return;
m.get(this).addEventListener("click",clickHandler);
}
Generator function
Blocking synchronization , Preload picture
// Blocking synchronization
function *loadImage(){
var arr=[];
for(var i=78;i<83;i++){
var img=new Image();
img.src=`./img/img_${
i}.jpeg`;
yield img.onload=function(){
arr.push(this);
g.next();
}
}
arr.forEach(item=>console.log(item.src));
}
var g=loadImage();
g.next();
边栏推荐
- Aragon creates Dao polygon BSC test network
- Leetcode-190. inverting binary bits
- Map tiles: detailed explanation of vector tiles and grid tiles
- leetcode-136.只出现一次的数字
- 接口调不通,如何去排查?没想到10年测试老鸟栽在这道面试题上
- 夜神模拟器抓包微信小程序
- 【架构】评分较高的三本微服务书籍的阅读笔记
- PHP generates random numbers (nickname random generator)
- Li Kou sword finger offer 51. reverse order pairs in the array
- Shell basic concepts and variables
猜你喜欢

基于神经网络的帧内预测和变换核选择

GO语言-栈的应用-表达式求值

gicv3 spi register

Realize the mutual value transfer between main window and sub window in WPF

今日睡眠质量记录75分

Cool operation preheating! Code to achieve small planet effect

Use non recursive method to realize layer traversal, preorder traversal, middle order traversal and post order traversal in binary tree

MySQL practice -- master-slave replication

Leetcode · daily question · 1331. array sequence number conversion · discretization

Can second uncle cure young people's spiritual internal friction?
随机推荐
用非递归的方法实现二叉树中的层遍历,先序遍历,中序遍历和后序遍历
Excellent performance! Oxford, Shanghai, AI Lab, Hong Kong University, Shangtang, and Tsinghua have joined forces to propose a language aware visual transformer for reference image segmentation! Open
JS method of splitting strings
Countdown 2 days! 2022 China Computing Conference: Mobile cloud invites you to meet with computing network for innovative development
火山石投资章苏阳:硬科技,下一个10年相对确定的答案
Operator3-设计一个operator
Resolve browser password echo
paddleClas分类实践记录
从手机厂高位“出走”的三个男人
Paddleclas classification practice record
Use non recursive method to realize layer traversal, preorder traversal, middle order traversal and post order traversal in binary tree
微念“失去”李子柒的这一年
Gamestop bear market entered NFT trading, and established game retailers took advantage of Web3 to make a second spring
How does the vditor renderer achieve server-side rendering (SSR)?
Kotlin learning notes 3 - lambda programming
MySQL practice -- master-slave replication
[apue] 文件中的空洞
What is the optimization method of transaction and database
Why is crypto game changing the game industry?
[报错]使用ssh登陆到另一台机器后,发现主机名还是自己|无法访问yarn8088