ES6 新增了很多特性,这里罗列了一些常用的,供大家参考。
ES6常用方法罗列
let、count
iterable (迭代器类型): Array 、 Map 、 Set ,可以通过 for … of 遍历
箭头函数
test=(param)=>{}
promise
向对象添加属性
const a ={id:1};
const b ={...a , pwd :"123"};// a 克隆成 b ,并在 b 中添加 pwd 属性
合并对象
//方法一
const a ={id:1};
const b ={ pwd :"123"};
constc ={...a, ...b };// ...为扩展运算符
//方法二
let obj1={ a :1};
let obj2={ b :2};
let obj3={ c :3};
let obj4= Object.assign (obj1,obj2,obj3);
console.log(obj1);//{ a :1, b :2, c :3}
console.1og(obj2);//{ b :2}
console.log(obj3);//{ c :}
console.log(obj4);//{ a :1, b :2, c :3}
删除属性
let old ={
id :1,
age :21,
name :"zhg"
};
//方法一
let {
name,
...news
}= old;
console.log(news);//{ id :1, age :21}
//方法二
let newS =(({ id , age })=>({ id , age }))( old );
console.log(newS);//{ id :1, age :21}
调整属性位置
let old ={
age :21,
name :"zhg",
id :1
};
let news ={ name : undefined , ...old };
// let news ={...old , name }//{ age :21, id :1,name:"zhg"}
console.log(news);//{ name :"zhg", age :21, id :1}
// let organize = object =>({ id : undefined ,.. object });
// let news= organize(old);
// console.log(news);
重命名对象属性
let old ={
age :21,
name :"zhg",
id :1
};
//方法一
let rename =({ id, ...old })=>({ ID : id, ...old });
let news = rename(old);
console.1og(news);//{ ID :1, age :21, name :"zhg"}
//方法二
let { id : IDD , name : Name }= old;
console.log(IDD);//1
//不能获取改变值的对象,只能获取改变名称的值
条件属性
let old ={
age :21,
name :"zhg",
id :1
};
let pwd ="pwd";
let blank ="";
let news={...old , ...(pwd &&{ pwd }), ...( blank &&{ blank })};
console.log(news);//{ age :21, name :"zhg", id :1, pwd :"pwd"}
数组元素位置交换
let list =[0,1,2,3,4,5];
[list[1],list[3],list[5]]=[list[5], list[1], list[3]];
console.log(list);//[0,5,2,1,4,3]
字符串新增方法
- includes(str,start)
- startsWith(str, start)
- endsWith(str, length)
let str = "ABCDEFG";
let result = str.startsWith ("B",2);
console.log(result);//0: false ;1:ture;2:false
对象赋值解构
//数组
let [a, b, c, d ]=[1,2,3,4];
console.log(a);// a =1; b =2; c =3; d =4;
//对象
let obj ={
name : "zhg",
say(){ console.log("zhg")}
}
// ==> let obj ={ name :"zhg", say :()=> console.log("zhg")}
obj.say();// console.log: zhg
函数传参解构
let arr=["abc",2,3];
function fn1([a, b, c]){
console.log(a);// abc
console.log(b);// 2
console.log(c);//3
}
fn1(arr);
// 暂不支持如下方法解构
let obj = {
a:"a",
B:"b",
c:[1,2,3]
}
let {a, B, c:[d,e,f]} = obj
console.log(e);// 不支持
数组去重
let arr =[1,2,3,4,5,4,3];
let set = new Set(arr);
let newArr = Array.from(set);
console.1og(newArr);//[1,2,3,4,5]
数组拷贝
let arr = [1,2,3];
let arr2= arr;
let arr3=[ ...arr ];
console.log(arr2===arr);// true 是一个数组
console.log(arr3===arr);// false不是同一个数组
字符串转数组
let str = "abcd";
let arr =[...str];
console.log(arr);//['a', 'b', 'c','d'];
网友评论