前端学习小结

113 阅读3分钟

1、DOM 事件相关

1.1、事件委托

1.1.1、背景

  1. 给大量的button添加点击事件,一个一个绑定?
    • No,仅仅需要给button们的祖先绑定(这样可以省内存)
  2. 怎样监听还不存在的对象?
    • 监听祖先元素,等到点击的时候再去判断(这样可以监听动态的元素)

1.1.2、定义

  • 绑定在父元素的事情,用户可以通过子元素触发。从JavaScript高级程序设计上讲,事件委托就是利用事件冒泡机制,只指定一个事件处理程序,就可以管理某一类型的所有事件。

1.2、阻止默认事件

  • w3c 的方法是 e.preventDefault(),IE 则是使用 e.returnValue = false
x.addEventListener('wheel',(e)=>{ e.preventDefault() }) 

1.3、阻止冒泡

  • w3c 的方法是 e.stopPropagation(),IE 则是使用 e.cancelBubble = true
level3.addEventListener('click',(e) => {e.stopPropagation() //阻止冒泡},false)

2、实现数组去重

设有数组 array = [1,5,2,3,4,2,3,1,3,4],你要写一个函数 unique,使得unique(array) 的值为 [1,5,2,3,4]

2.1 sort

  • 利用sort()排序方法,然后根据排序后的结果进行遍历及相邻元素比对。
unique = (array) => { 
    arr = arr.sort()
    var arrry= [arr[0]];
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[i-1]) {
            arrry.push(arr[i]);
        }
    }
    return arrry;
}

2.2 使用 Set

unique = (array) => { 
  return Array.from(new Set(array)) // return [...new Set(array)]
}
unique([1,5,2,3,4,2,3,1,3,4])

缺点:API太新,旧的浏览器不支持,看上去简单

2.3 用Map数据结构去重

  • 创建一个空Map,遍历需要去重的数组,把数组的每一个元素作为key存到Map中。由于Map中不会出现相同的key值,所以最终得到的就是去重后的结果。
unique = (array) => { 
let map = new Map(); 
let result = [] 
for (let i = 0; i < array.length; i++) {   
  if(map.has(array[i])) {
    // 判断 map 中是否已有该 key 
    continue 
  } else { 
    // 如果 map 中没有该 key,就加入 result 中 
    map.set(array[i], true);    
    result.push(array[i]); 
    }
  } 
return result; 
}
unique([1,5,2,3,4,2,3,1,3,4])
  • 缺点:API 太新,旧浏览器不支持

2.4 其他

unique = (array) => {
    const hash = []
    for(let i=0;i<array.length; i++){
        hash[array[i]] = true
    }
    const result = []
    for(let k in hash){
        result.push(k)
    }
    return result
}
unique([1,5,2,3,4,2,3,1,3,4])
  • 缺点:此法只支持数字或者字符串数组,如果数组里面有对象,比如 array = [{number:1}, 2],就会出错。

3.如何理解 JS 的继承

3.1 基于原型继承

// 基类(superclass)
function Parent(name,age){
    this.name = name;
    this.age = age;
}
// 基类-方法
Parent.prototype.say = function(){
    console.log('My name is:'+this.name);
}

// 子类
function Child(name,age) {
    Parent.call(this,name,age); //调用基类的构造函数
}

// 子类继承父类
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child // 构造器指回自己

// 创建类实例
var child = new Child('亦蔚然', '18');
console.log(child instanceof Parent) // true
console.log(child instanceof Child) // true

child.say()
console.log(child.age)

3.2 基于class继承

class Father{
    constructor(fatherName){
        this.fatherName = fatherName
    }
    say(){
        console.log('My name is:'+this.fatherName)
    }
}
class Child extends Father{
    constructor(selfName, fatherName){
        super(fatherName) // 得分点
        this.selfName = selfName
    }
    say(){
        console.log('my father's name:'+this.fatherName,'My name is:'+this.selfName)
    }
}
var child = new Child('蔚然', '');
child.say()

4.数组排序

给出正整数数组 array = [2,1,5,3,8,4,9,5];请写出一个函数 sort,使得 sort(array) 得到从小到大排好序的数组 [1,2,3,4,5,5,8,9];新的数组可以是在 array 自身上改的,也可以是完全新开辟的内存;不得使用 JS 内置的 sort API

4.1 冒泡排序

  • 重复访问数组元素,依次比较相邻两个元素,然后进行交换
function bubbleSort(arr){
    for(let i = 0; i < arr.length - 1; i++){
        for(let j = 0; j < arr.length - i - 1; j++){
            if(arr[j] > arr[j+1]){
                let temp = arr[j]
                arr[j] =arr[j+1]
                arr[j+1] = temp
            }
        }
    }
    return arr
}
console.log(bubbleSort([2,1,5,3,8,4,9,5]))

5. 对Promise的了解

5.1 Promise 的用途

  • Promise对象是JavaScript的异步操作解决方案,为异步操作提供统一接口,可以让异步操作写起来就像再写同步操作的流程,不必一层层的嵌套回调地狱,让回调地狱变得可控。

5.2 创建一个 new Promise

new Promise( (resolve, reject) => {} )

5.3 使用 Promise.prototype.then

const p1 = new Promise( (resolve,reject) => {
  resolve('success!')
} )

p1.then(value => {
  console.log(value)
}, reason => {
  console.error(reason)
})

5.4 使用Promise.all

var p = Promise.all([1,2,3,Promise.resolve(444)]);
console.log(p); // Promise { <state>: "fulfilled", <value>: Array[4] }

var p2 = Promise.all([1,2,3,Promise.reject(555)]);
console.log(p2); // Promise { <state>: "rejected", <reason>: 555 }

5.5 使用 Promise.race

var p1 = new Promise( (resolve,reject) => {
  setTimeout(resolve,500,"one");
} )
var p2 = new Promise(() => {
  setTimeout(resolve,200,"two")
})

Promise.all([p1,p2]).then((value) => {
  console.log(value);
},(reason) => {
  console.log(reason)
}) //"two" 两个都完成,但是p2更快

var p3 = new Promise((resolve, reject) => {
  setTimeout(reject,100,"three")
})

Promise.all([p3,p2]).then((value) => {
  console.log(value);
},(reason) => {
  console.log(reason)
}) // three 因为p3更快,所以失败了