JavaScript常用特性和新特性--总结

一,字符串新增方法

1,includes
let str='hello world';
console.log(str.includes('lo'));//true

console.log(str.repeat(2));//hello worldhello world
console.log(str.startsWith('hello'));//true ,参数2为查找的位置
console.log(str.endsWith('w',7));//true,参数2为查找的字符串长度

二,键值对重名简写

function f(){        
    let name='s';
    let age=24;
    return{
        name,age
    }
}
const s1 = {
    name: 'st',
    getName(){  // 省略冒号:和function关键字
        console.log(this.name);
    }
}

提供对象合并

const s2 = Object.assign({age:24},s1);
console.log(s2);//{age: 24, name: "st", getName: ƒ}

数据解构和rest参数

const {name,age} =s2;  
console.log(name);  //st

// 数组解构 
const arr = [1, 2, 3];
const [a, b, c] = arr; // 1, 2, 3

// rest参数,返回的是一个对象
const obj={a:1,b:2,c:3};
const {a,...rt}=obj;
console.log(rt); //{b: 2, c: 3}

对象合并简化

console.log({...obj,d:4});//{a: 1, b: 2, c: 3, d: 4}
console.log([...arr,4]); //[1, 2, 3, 4]

三,Set是ES6新的数据解构(类数组),它的成员都是唯一的

const a =[1, 2, 3];
const b = [2, 3, 4];
// 并集
const s = Array.from(new Set([...a, ...b])); // [ 1, 2, 3, 4 ]
// 交集、差集
const bSet = new Set(b);
const interestSet = a.filter(v => bSet.has(v)); // [ 2, 3 ]
const interestSet = a.filter(v => !bSet.has(v)); // [ 1 ]

四,ES7在ES6的基础上添加:求幂运算符(**)

Math.pow(2, 3) === 2 ** 3    // 8

includes()和indexOf()

[1, 2, 3].indexOf(2) > -1 // true
等同于:
[1, 2, 3].includes(2) // true

两者这都是通过===进行数据处理,但是对NaN数值的处理行为不同。
[1, 2, NaN].includes(NaN);// true
[1, 2, NaN].indexOf(NaN) ; // -1

猜你喜欢

转载自blog.csdn.net/yzx15855401351/article/details/108272628