1. var存在的两大弊端:
- 允许重复声明(非严格模式下)
- 函数作用域
(let const不允许重复声明,有块作用域。函数作用域也是一种特殊的块作用域)
2.在实际开发中,const的使用>let的使用>var的使用。const变量,需要重新赋值的时候一般声明一个新变量。
3.箭头函数的作用:
-
使函数写法更简洁(只能用于匿名函数中)
function square(a){return a*a*a} × const square = function(a){return a*a*a} √
-
函数返回值可以隐性返回(函数只有一行返回值)
const square = a =>a*a*a;
-
不重新绑定this
console.log(this) //window document.getElementById("button"). addEventListener('click',function(){ console.log(this); //普通函数重新绑定this,指向button这个元素节点 this.classList.add("select"); }) console.log(this) //window document.getElementById("button"). addEventListener('click',()=>{ console.log(this); //由于箭头函数不会重新绑定this,还是外层的window this.classList.add("select"); //!!!报错 不存在add属性,因为this不是元素节点 }) console.log(this) //window document.getElementById("button"). addEventListener('click',function(){ this.classList.add("select"); setTimeout(function(){ this.innerHtml = "apple"; //!!!报错 因为普通函数重新绑定this,setTimeout无人调用,此时this指向window。 },1000) }) 解决方法---手动修改this指向(不推荐): console.log(this) //window document.getElementById("button"). addEventListener('click',function(){ this.classList.add("select"); const $this = this; setTimeout(function(){ $this.innerHtml = "apple"; // 此时$this保存了对button节点的指向 },1000) }) 解决方法---改写箭头函数: console.log(this) //window document.getElementById("button"). addEventListener('click',function(){ this.classList.add("select"); setTimeout(()=>{ this.innerHtml = "apple"; // 匿名函数不重新绑定this,仍然指向外层button元素节点 },1000) })
4.模板字符串的作用
- 更简洁直观的书写拼接字符串
- 直接输出带有格式的字符串
5.二分法查找 binary search
- 例题:leetcode704
- 思想:
- 注意:mid = left +(right-left)/2 而不是mid = (left+right)/2
虽然结果一样,但是避免了整型溢出的情况
6.哈希表解两数之和
-
例题:leetcode1
-
思想:
-
补充:
set和map存储数据:纯hash,性能优于object
set > array 数据保证唯一性,无重复的值var numberSet = new Set(); //创建一个set numberSet.add(); //加入值 ,自动去重 numberSet.delete(); //删除值(返回布尔值) numberSet.has(); //判断是否有目标 numberSet.size; //求长度 numberSet.forEach(function(){}) //遍历
map > object
var map = new Map(); //创建一个map
map.set(key,value); //有则更新,无则添加
map.delete(); //删除值(返回布尔值)
map.get(key); //获取某个值
map.has(key); //判断是否有目标
map.size; //求长度
for...of...
for...in... //遍历
7.字符串逆序的方法:
-
使用内置函数 splice reverse join
str.split('').reverse().join('');