系列(四)

184 阅读2分钟

1.async 和 await使用

 const repeatFunc = repeat(console.log, 4, 3000);
     repeatFunc('hellworld');  //每隔三秒打印一次 helloworld 共打印四次。
     
    function sleep1(wait) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, wait);
      });
    }
    function repeat(func, times, wait) 
    {
      return async function () {
        for(var i = 0; i < times; i++) {
          await sleep1(wait);
          func.apply(this, arguments);
        }
      }
    }

2. 计算题

/**写个JavaScript函数来判断是否大于18岁,
 * 比如传入1993-10-10,返回true,传递2003- 10-10返回false;
 */
 
 function isAdult(str){
  let [birYear, birMonth, birDate] = str.split("-").map(Number);
  let today = new Date();
  let [Y, M, D] = [today.getFullYear(), today.getMonth() + 1, today.getDate()];
  if (Y - birYear < 18) {
    return false;
  } else if (Y - birYear === 18) {
    if (M - birMonth < 0) {
      return false;
    } else if (M - birMonth === 0) {
      if (D - birDate < 0) {
        return false;
      }
    }
  }
  return true;
}

3.数组中forEach不能中断的解法

var arr = [1, 2, 3, 4, 5, 6, 7];
// foreach 正常不可以终端遍历过程。可以抛除一个异常终止循环。用some 和 every 可以轻松实现。
// some 返回true时终端遍历
// every 返回false时终端遍历,返回true继续遍历
  try {
    arr.forEach((item, index) => {
      console.log(item);
      if (item == 3) {
        throw new Error('break');
      }
    });
  } catch (e) {
    console.log(e);
  }
  console.log(11);
  console.log(112); //继续打印

4.jquery事件委托

on 是委托事件,利用的就是冒泡原理

$(selector).on(event,[selector],handler);

$("ul").on('click',function(){

  console.log('我是父级ul');

})

$('ul').on('click','li',function(e){

   e.stopPaptration();//为了不让点击li 使得他们的父级的事件也触发了,就阻止冒泡,这样就只为所有的li 执行事件,不会再执行到ul上去

   cnosole.log($(this).text());//当前被点击的那个li

})

5.promise 捕获错误之后继续执行

Promise.resolve().then(() => {
  console.log('ok1')
  throw 'throw error1'
}).then(() => {
  console.log('ok2')
}, err => {
  // 捕获错误
  console.log('err->', err)
}).then(() => {
  // 该函数将被调用
  console.log('ok3')
  throw 'throw error3'
}).then(() => {
  // 错误捕获前的函数不会被调用
  console.log('ok4')
}).catch(err => {
  console.log('err->', err)
}).then(()=>{
  console.log(1);
})
/**
 * ok1
err-> throw error1
ok3
err-> throw error3
1 */

6.promise 中断 可以使用 Promise.race()

最先一个被resolve或者被reject的结果就是p的resolve或者reject的结果。所以后续的promise的resolve和reject都不会再被执行了

7.vue 父组件中调用子组件函数的方法

在父组件中调用子组件的方法:

 1.给子组件定义一个ref属性。eg:ref="childItem"

 2.在子组件的methods中声明一个函数。eg: useInPar:function (str) {console.log(str)}

 2. 在父组件的中声明一个函数,并通过this.$refs.childItem.userInPar来使用子组件中声明的函数。
父组件:

<template>
 <child-item ref='child' />
  <button @click='useChildFun'></button>
 </template>
 <script>

methods() { useChildFun:function(){ this.$refs.child.usedInPar('调用子组件中的方法');

   //this.$refs.child.$emit('childMethod') // 方法1
  // this.$refs.child.callMethod() // 方法2

} }


子组件:

methods () { usedInPar(str){ console.log(str); } }