ES6Day02: string extension method and template string, expansion operators, new array api, new objects api, Map, Set, Proxy, Reflect, simple two-way data binding

table of Contents

0x00 string extension method and template string

0x01 ... Extended operator using

1. To achieve deep copy of the array

2. striped array

3. The parameters passed to function

0x02 new array of related api

New features 0x03 ES6 objects and new methods

0x04 Map and WeakMap

0x05 Set and WeakSet

0x06 Map, and the difference between Array and Object Set

0x06 Proxy and Reflect

0x07 simple two-way data binding


0x00 string extension method and template string

1.ES5 handle Unicode flaw:

ES5 allowed the use of \ uxxxx represented in the form of a character. Wherein xxxx indicates the character of Unicode code points , this representation is limited codepoint \ u0000- \ uFFFF between strings. Outside this range must be expressed in the form of two double-byte, but ES5 can not correctly identify the character has two bytes.

In ES6, js increased \ u0000- \ character support beyond the scope of uFFFFUnicode

ES6 solution: beyond the point of the character code consisting of two bytes are placed in a pair {} may be displayed correctly.

// ES5
{
    const str = "\u20bb";
    console.log(str);
    const str2 = "\u20bb7";
    console.log(str2);
}
// ES6
{
    const str2 = "\u{20bb7}";
    console.log(str2);
}

2. The new string traversal methods

for of

// ES6
{
    const str2 = "\u{20bb7}";
    for(let i=0;i<str2.length;i++){
        console.log("for循环",str2[i]);
    }
    for(let word of str2){
        console.log("for of循环",word);
    }
}

You can see unicode character traditional for loop can not handle out of range. And for of circulation can. It recommended more use for of circulation.

3. The new string functions

Determining whether the string contains several methods specified string.

Includes ( 'substring') determines whether the character string contains the substring

startsWith ( 'substring' [from the first several starts]) is determined not to string beginning with the substring. The default is to start from No. 0.

endsWith ( 'substring' [substring than the end position is not the position]) is determined not to end the string substring

let string = "php is the best language";
console.log(string.includes("best"));
console.log(string.startsWith("php"));
console.log(string.startsWith('is',4));
console.log(string.endsWith("language"));
console.log(string.endsWith("e",string.length));

Repeating string, ES5 repeated string can only be used for recycling

REPEAT (n) Returns a new string that represents the original string is repeated n times.

let str ="欧拉";
str = str.repeat(10);
console.log(str);

String completion:

The first parameter is the length of the completion string, the second argument is a string for completion.

The return value is a string completions

padStart (length, str) for completion of the head;

padEnd (length, str) tail for completion;

let str ="欧拉";
str = str.repeat(100);
str = str.padStart(str.length+100,"木大");
console.log(str);

Template string:

Backticks to cause the string, line, and spaces are outputted as, html tag is parsed. Js encountered variable, $ {variable name} variable will be resolved. If the variable is not a string type, it will be implicit type conversion string type. $ {} And can be placed within any js expression . (Operations, function calls, nested, or even call itself)

let name ="bo良ki影";
let age =33;
console.log(`我叫${name},今年${age}岁`);

0x01 ... Extended operator using

Extended operator can expand the array: array name ...

1. To achieve deep copy of the array

This can only achieve a shallow copy, the copy that is just the first address of the array to the list2

let list=[1,2,3,4];
let list2 = list;
list.push(5);
console.log(list2);
console.log(list);

How deep copy of it?

... Extended operator simply expanded to represent the array element, and with a [] enclosed to form a new array

let list=[1,2,3,4];
let list2 = [...list];
list.push(5);
console.log(list2);
console.log(list);

2. striped array

let totalList=[1,"xiaoming","xiaohong","xiaogang"];
let [,...nameList]=totalList;
console.log(nameList);

3. The parameters passed to function

let numList = [1,2,3,5,6];
function sum(a,b,c,d,e){
    return a+b+c+d+e;
}
console.log(sum(...numList));

0x02 new array of related api

1.fill (a number [, start, end])

The default will replace all data in the array of a number. Alternatively range specified start and end, the front opening and closing section.

The return value is the new array after replacement

Original array changed

let numList = [1,2,3,5,6];
let list2 =[...numList].fill(8,1,4);
console.log(list2);
console.log(numList.fill(3));
console.log(numList);

2.find and findIndex

find only return the first found, returned to find results

findIndex above, but returns the index results found.

let list = [{"title":"es5","id":6},{"title":"es6"},{"title":"es5","id":5}];
let ret = list.find(function(item){
    return item.title=="es5";
})
console.log(ret);

Whether there is a value 3.includes (a value) to determine the array, only a simple type of data used to determine

4. Expand the two-dimensional array

Method One: Only expanded into a two-dimensional array array

let list = [[1,2,3,4,5],[2323,34,414,]];
let flatList =[].concat(...list);
console.log(flatList);

Method two: direct call flat ([expanded several times]), for example, you want to expand into three-dimensional array of one-dimensional array, you only need to pass 2. Default expansion only once.

let list = [[1,2,3,4,5],[2323,34,414,]];
let flatList =list.flat();
console.log(flatList);

5.map data mapping

Each element of the array reference will be passed item. map the return value will form a new array

let jsonList = [{"title":"es6","status":1},{"title":"jsp","status":0}];
let displayList = jsonList.map(function(item){
    return {
        "name":item.title,
        "status":item.status?"已登录":"未登录"
    }
}) 
console.log(displayList);

6.reduce each element of the array once callback performed in ascending order, and then aggregated to a value of the callback return value.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

https://www.runoob.com/jsref/jsref-reduce.html

For example: the number of statistics for each string of letters appears

let str= "asdasfagag";
let result = str.split('').reduce(function(hashTable,current){
    hashTable[current]?hashTable[current]++:hashTable[current]=1;
    return hashTable;
},{})
console.log(result);

Empty object as an initial value. The initial value of a start will be assigned to hashTable. Then each value in the array will be assigned to the current one by one to perform the callback function, the return value of each callback function will return to the hashTable. Down through the complete array. Function returns the result.

7.Array.from array object classes (with attributes and may traverse the length) into an array. For example: String

let str ="hello world";
let arr = Array.from(str);
console.log(arr);

New features 0x03 ES6 objects and new methods

1. Object ... extended operator using

(1) deep copy target

First you need to install plug-ins: npm install babel-plugin-transform-object-rest-spread

After installation is complete, add "plugins" in the .baberlrc: [ 'transform-object-rest-spread']

let obj={name:'xiaoming',age:12};
let obj2 = {...obj};
console.log(obj2);

(2) Set the default value to the subject

let obj={name:'xiaoming',age:12};
let obj2 = {...obj,name:'Jack'};
// 表示将name替换为Jack
console.log(obj2);

(3) combining objects

let obj={name:'xiaoming',age:12};
let info={job:'programmer',wife:'xiaohong'};
// 将两个对象合并
let obj2={...obj,...info};
console.log(obj2);

Pit: Simple data types, using extended operator is no problem. But if the extension operator launched later, or an object, we just copy a pointer

2. The new operation on an object

<1> ES6 object:

(1) Property name attribute values ​​of the same name and the time to write only one is enough.

(2) method can be omitted function key, you can direct method name in parentheses.

let name="xiaoming";
let age="33";
let objEs5={
    name:name,
    age:age,
    sayHello:function(){
        console.log("这是ES5对象的写法");
    }
};
let objEs6={
    name,
    age,
    sayHello(){
        console.log("这是ES6对象的写法");
    }
}
console.log(objEs5);
console.log(objEs6);

Object wording ES6 can understand ES5 objects wording of syntactic sugar, more simple and intuitive.

<2> the calculated attribute name

Property name when the object is a variable time.

// es5的写法
let key='name';
let es5obj={};
// let es5obj[key]="xiaoming";
console.log(es5obj);
// es6的写法
let es6obj={
    [key]:"xiaoming"
}
console.log(es6obj);

<3> New method

1.Object.is():

=== and almost the same, except that the determination of whether NaN equal NaN

console.log(Object.is(NaN,NaN));//true
console.log(NaN === NaN)//false

2.Object.assign(dst,src)

Object deep copy. (Only one layer deep copy)

let obj = {name:"xiaoming",age:18,info:{height:180,weight:60}};
let obj2 ={}
obj.info.height = 175;
Object.assign(obj2,obj);
console.log(obj2);

3.Object.keys () returns an array of object linkages

var json = {"name":"xiaoming","age":18};
let obj={};
for(let key of Object.keys(json)){
    obj[key] = json[key];
}
console.log(obj);
console.log(Object.keys(json));

4.Object.values ​​() Returns the value of an object consisting of an array of

5.Object.entries () returns an object consisting of an array of keys

0x04 Map and WeakMap

因为js中的对象只能用字符串作为键名,不能以数组,对象等其他类型作为键名,所以,就提出了Map对象。

Map对象

用于保存键值对,任何值(对象或者原始值)都可以作为一个键或者一个值

//添加元素
let map = new Map();
map.set([1,2,3],'number');
// map.set(键,值) 返回值是当前的map对象,所以可以采用一种链式的写法
map.set([4,5,6],"pagenum").set([32,34],"totalNum");
console.log(map);

// 在初始化的时候添加元素(二维数组)
let map2 = new Map([
    ["name","xiaoming"],
    ["age",19],
    ["height",180]
])
console.log(map2);
console.log(map2.size);
//改
map2.set("name","xiaohong");
console.log(map2);

//查 
console.log(map2.get("name"));
// 如果有该属性则返回该属性,没有则返回undefined
console.log(map2.has("npy"));
//如果有该属性则返回true,没有则返回false

//删
map2.delete("height");
console.log(map2);
map2.clear()//清空所有键值对

//遍历
for(let key of map2.keys()){
    console.log(key);
}
for(let value of map2.values()){
    console.log(value);
}
for(let entry of map2.entries()){
    console.log(entry);
}
// 默认遍历entries
for(let entry of map2){
    console.log(entry);
}

2.WeakMap对象

只接受对象作为一个键名,不接受其他类型的数据作为键名

使用方法同Map,但是没有clear 和size,无法遍历

0x05 Set和WeakSet

Set集合数据类型,即值不会有重复项,其余和数组一样

遍历方法基本同上,但是set中的keys和value是一样的

使用场景:数组去重,直接将数组传给set即可。然后用from将set这个类数组对象转换为数组。

let arr = [1,1,1,23,54,54,54,3];
let set = new Set(arr);
arr = Array.from(set);
console.log(set);
console.log(arr);

WeakSet 和Set的区别:

1.WeakSet的元素只能是对象,对象也是弱引用,即WeakSet无法遍历

2.没有size,也没有clear

0x06 Map、Set与Array及Object间的区别

1.从增删改查四个方面来比较

let arr=[];
let obj={};
let map = new Map();
let set = new Set();
let gooditem = {fruit:"apple"};
//增
arr.push(gooditem);
obj["fruit"]="apple";
map.set("fruit","apple");
set.add(gooditem);
console.log("add",arr,obj,map,set);
//查
let resultarr = arr.includes(gooditem);
let resultobj = "fruit" in  obj;
let resultmap = map.has('fruit');
let resultset = set.has(gooditem);
console.log("find",resultarr,resultobj,resultmap,resultset);
//删除
let index = arr.findIndex(function(item){
    return item.fruit;
})
arr.splice(index,1);
delete obj.fruit;
map.delete("fruit");
set.delete(gooditem)
console.log("add",arr,obj,map,set);;

2.它们之间的类型转换

(1)对象转map

//对象转map
let obj = {"name":"xiaoming","age":15};
console.log(Object.entries(obj));//返回是一个键值对数组
let map = new Map(Object.entries(obj));
console.log(map)

(2)map转对象:fromEntries()

//map转对象
let obj2 = Object.fromEntries(map);
console.log(obj2);

(3)数组转set

let arr = [1,2,3,3,2,1];
let set = new Set(arr);
console.log(set);

(4)set转数组

let arr2 = Array.from(set);
console.log(arr2);

0x06 Proxy和Reflect

proxy代理,代理的是对象的一些操作,例如:对象的读取操作和设置操作 proxy可以拦截下来,来进行一些自定义的处理,即做一个中间层,就像批发商代理商一样。

创建代理对象, new Proxy(需要代理的对象,{get方法,set方法})

get:function(接收拦截的对象,接收拦截对象的键)方法用来拦截对对象的读取操作。

set:function(接收拦截的对象,接收拦截对象的键,接收设置的值) 用来拦截对象的设置操作

has:function(接收拦截的对象,接收拦截对象的键) 用来拦截key in obj 操作

deleteProperty:function(接收拦截的对象,接收拦截对象的键)拦截删除操作

ownKeys(target)拦截Object.keys()操作

let account = {
    id:24,
    name:'admin',
    phone:'3214155189',
    create_time:'2019',
    _wife:'小红'
}

let accountProxy = new Proxy(account,{
    //拦截”account对象 的 读取和设置操作“
    get:function(target,key){
        switch(key){
            case 'phone':
                return target[key].substring(0,3)+'*****'+target[key].substring(7,10);
            case 'create_time':
                return target[key].replace('2019','2020');
            default:
                return target[key]               
        }
    },
    //拦截设置操作
    set:function(target,key,value){
        if(key === 'id'){
            return target[key];//如果是id,就不让他设置
        }else{
            return target[key]=value;
        }
    },
    //拦截in操作
    has:function(target,key){
        if(key in target){
            console.log(`${key}:`,target[key]);
            return true;
        }else{
            console.log("没有该属性");
            return false;
        }
    },
    //拦截delete操作
    deleteProperty:function(target,key){
        if(key.indexOf('_')==0){
            console.warn("私有属性不能被删除");
            return false;
        }else{
            delete target[key];
            return true;
        }
    },
    //拦截遍历操作
    ownKeys(target){
        return Object.keys(target).filter(function(item){
            return item!='id' && item.indexOf('_')!=0;
        })
    }
})
console.log('拦截读取',accountProxy.phone,accountProxy.create_time);
accountProxy.id=123;
accountProxy.name = "xiaohong";
console.log('拦截设置',accountProxy.id,accountProxy.name);
console.log("拦截in","name" in accountProxy);
console.log("删除",delete accountProxy['_wife']);
console.log("拦截Object.keys",Object.keys(accountProxy));

Reflect:对象的所有操作都可以用Reflect来代替。

建议以后操作对象,都用Reflect,更符合函数式编程的理念,并且语义上更加明确。

let obj = {
    id:24,
    name:'admin',
    phone:'3214155189',
    create_time:'2019',
    _wife:'小红'
}
console.log(Reflect.get(obj,"name"))
Reflect.set(obj,'name','Jack')
console.log(obj.name);
Reflect.has(obj,"name");//'name' in obj

0x07 实现简单的双向数据绑定

window.οnlοad=function(){
    // 获取dom元素
    const inputObj=document.getElementById('input');
    const txtObj = document.getElementById('txt');
    // 初始化代理对象
    const obj = {};
    // 配置代理选项
    const handler= {
        get:function(target,key){
            return Reflect.get(target,key);
        },
        set:function(target,key,value){
            if(key=='text'){
                inputObj.value=(inputObj.value === value)?inputObj.value:value;
                txtObj.innerHTML=value;
            }
            return Reflect.set(target,key,value);
        }
    }
    //代理实例
    let objProxy = new Proxy(obj,handler);
    // 给input添加键盘键入事件
    inputObj.addEventListener('keyup',function(e){
        objProxy.text = e.target.value;
        console.log(objProxy);
    },false);
    objProxy.text = '124';
}

 

发布了156 篇原创文章 · 获赞 19 · 访问量 8922

Guess you like

Origin blog.csdn.net/weixin_43415644/article/details/104212395