JS 常用方法

62 阅读1分钟

递归寻找数组中符合条件的对象

    const findObj = (arr, id) => {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].deptCode === id) {
          return Object.assign({}, arr[i]);
        }
        if (arr[i].children && arr[i].children.length) {
          const item = getDepartment(arr[i].children, id);
          if (item) return item;
        }
      }
    };

将变量中的下划线转成驼峰命名

      function toHump(name) {
        return name
          .toLocaleLowerCase()
          .replace(/\_(\w)/g, function (all, letter) {
            return letter.toUpperCase()
          })
      }
      toHump('LETTER_USER_NAME') // letterUserName

将驼峰转为下划线

function toLine(name) { return name.replace(/([A-Z])/g,"_$1").toLowerCase(); } toLine('letterUserName') // letter_user_name

封装ajax

      class Api {
        response({ url, method = 'get', data }) {
          return new Promise((resolve) => {
            // 1.实例化ajax对象
            let xhr = new XMLHttpRequest()
            //   2.设置请求方法和地址
            url = baseUrl + url
            xhr.open(method, url)
            // 3.设置请求头 post请求才需要设置
            method === 'post' &&
              xhr.setRequestHeader('Content-Type', 'application/json')
            // 4. 发送请求
            xhr.send(JSON.stringify(data))
            //   5.注册回调函数
            xhr.onload = function () {
              resolve(JSON.parse(xhr.responseText))
            }
          })
        }
        get(url) {
          return this.response({
            url,
            method: 'get',
          })
        }
        post(url, data) {
          return this.response({
            url,
            method: 'post',
            data,
          })
        }
      }

递归算法

计算n的阶乘

也就是 1234...n的值

function times(n){
  if(n===1){
    return 1
  }
  return n*times(n-1)
}
console.log(times(5));
/**
 * 执行过程
 * 5*times(5-1)
 * 4*times(4-1)
 * 3*times(3-1)
 * 2*times(2-1)
 * 
 * 2*1
 * 3*2
 * 4*6
 * 5*24
*/

深度拷贝

function deepClone(obj) {
    if (obj === null) {
      return null;
    }
    if (typeof obj !== 'object') {
      return obj;
    }
    if (obj instanceof RegExp) {
      return new RegExp(obj);
    }
    if (obj instanceof Date) {
      return new Date(obj);
    }
    let newObj = new obj.constructor();
    for (let key in obj) {
      newObj[key] = deepClone(obj[key]);
    }
    return newObj;
  }

斐波拉契数列

有一对兔子, 从出生的第三个月起每个月会生一对兔子, 小兔子长到第三个月起每个月也会生一对兔子, 假如兔子不死, 那么第N个月有多少对兔子

// 固定公式: 第N个月的兔子总对数 = 第N-1个月的总数+第N-2个月的总数
function fun(n){
    if(n<=0){
      return 0
    }
    if(n<=2){
      return 1
    }
    return fun(n-1)+fun(n-2)
}