一.const优于let的几点,多用const
1.const可以提醒大家,不要被改变
2.const比较符合函数式编程,(在函数式编程里面,运算是不能改变值的,只能新建值,有利于分布式编程,因为值不变)
3.js编译器对const进行了优化,有利于程序的运行效率(本质的区别:编译器内部对其处理机制)
let a='22'; a='11'; console.log(a);//11 let c=[]; c.push('a'); console.log(c);//["a"]
二.对象的解构
数组
const s=['a','b','c']; const [one,two,three]=s; console.log(three);//c
对象
function test(){ return{r:1,o:2} } const result = test(); const {r,o} =result; //const {o,r} =result; console.log(r);//1
三.字符串模板
const aaa ="hello"; const bbb = "world"; const ccc = `for ${aaa} ${bbb} bar`; console.log(ccc);//for hello world bar console.log(ccc.startsWith("for"));//true 以什么开头 console.log(ccc.endsWith("bar"));//true 以什么结尾 console.log(ccc.includes("or"));//true 包含 const ddd = txt `for ${aaa} ${bbb} bar`; function txt(strs,...values){ console.log(strs);//["for ", " ", " bar", raw: Array(3)] console.log(values);//["hello", "world"] }
四.对象和数组
const aa = "您好啊"; const resulta =Array.from(aa); console.log(resulta);//["您", "好", "啊"] const testa=["水果","水",...aa]; console.log(testa);//["水果", "水", "您", "好", "啊"] const k = "arr"; const testb ={ k1:1, aa, testa, q(){ console.log("企鹅") }, [k+1]:1 } console.log(testb);//{k1: 1, aa: "您好啊", testa: Array(5), q: ƒ, arr1: 1} testb.q();//企鹅
ps:下面的两种写法,第一种不建议,建议按第二种写,当初期不知道要不要扩张,可以先写上
const ar={}; Object.assign(a,{x:3});
const arb ={x:null}; arb.x=3; console.log(arb);//{x: 3}
判断
console.log(NaN===NaN);//false console.log(Object.is(NaN,NaN));//true
原型链
const eat = {getEat(){return "鸡腿"}} const drink = {getDrink(){return "啤酒"}} let sunday = Object.create(eat); console.log(sunday.getEat());//鸡腿 console.log(Object.getPrototypeOf(sunday));//{getEat: ƒ} Object.setPrototypeOf(sunday,drink); console.log(sunday);//{}>__proto__:>getDrink:ƒ getDrink()+__proto__:Object console.log(sunday.getDrink());//啤酒 let sundays = { __proto__:eat, getDrink(){ return super.getDrink() + "可口可乐" } } sundays.__proto__=drink; console.log(sundays.getDrink());//啤酒可口可乐
五.函数
const fn = function pp(argu){ } console.log(fn.name);//pp
箭头函数
(()=>{ console.log("fn init")//fn init })();
同一个函数的两种写法,第二种为简写
const restles = [1,2,3].map(function(index){ return index *3 }) console.log(restles);//[3, 6, 9]
const restless = [1,2,3].map((index)=>index *3); console.log(restless);//[3, 6, 9]
函数的this指向
window.aas='30'; const aaar ={ ll:40, ps:function(){ const qqq ={ ll : 50, ptest:()=>{ console.log(this.ll) } } qqq.ptest(); }, } aaar.ps();//40??不懂
其他
function testsss(aaaaa=1,{options=true}={}){ console.log(aaaaa);//30 console.log(options);//111 } testsss(30,{options:111});
function ssrx (...results){ //替代了arguments,可以不要用了 console.log(results)//[30, {…}] } ssrx(30,{options:111});