前端常见笔试题

906 阅读1分钟

来源: 本人博客园文章

1. 实现一个函数,输入一个单词,返回输入单词是否符合全大写、全小写、首字母大写规则,正确返回true,错误返回false

const checkValid = (word) => {
    let toU = word.toLocaleUpperCase();
    let toL = word.toLocaleLowerCase();
    let initialsToU = word.charAt(0).toLocaleUpperCase() + word.slice(1).toLocaleLowerCase();
    if (initialsToU === word || toU === word || toL === word) {
      return true
    } else {
      return false
    }
    console.log(checkValid('china'))
}

2. 实现一个方法,数组为升序返回1,数组为降序返回-1,乱序返回0

const isSorted = (arr) => {
    let target = arr.toString().replace(/,/g, '')
    let riseTarget = arr.sort((a, b) => {
      return a - b
    }).toString().replace(/,/g, '')
    let dropTarget = arr.sort((a, b) => {
      return b - a
    }).toString().replace(/,/g, '')
    if (target === riseTarget) {
      return 1
    } else if (target === dropTarget) {
      return -1
    } else {
      return 0
    }
}
console.log(isSorted([3, 2, 1, 0]))

3. 实现一个节流函数, 它返回一个新函数,新函数即时连续多次执行, 在wait的时间执行一次。并要求此节流函数第一次运行就会执行fn

const throttle = (fn, wait) => {
    let isNext = true;
    return () => {
      if (!isNext) return;
      isNext = false;
      setTimeout(() => {
        fn()
        isNext = true;
      }, wait)
    }
}
window.addEventListener("resize", throttle(() => console.log('我是节流函数'), 1000))