面试手写第六期

一. Promise封装Ajax请求

function getJSON(url) {
    
    
  return new Promise((resolve, reject) => {
    
    
    let xhr = new XMLHttpRequest();
    // 新建一个HTTP请求
    xhr.open('get', url, true);
    // 设置状态的监听函数
    xhr.onreadystatechange = function () {
    
    
      if (this.readyState !== 4) return;
      if (this.status === 200) {
    
    
        resolve(this.response);
      } else {
    
    
        reject(new Error(this.statusText));
      }
    };
    xhr.onerror = function () {
    
    
      reject(new Error(this.statusText));
    };
    xhr.responseType = 'json';
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.send(null);
  });
}

二. setTimeout实现setInterval

function mySetTimeout(func, delay) {
    
    
  let timer = null;
  const interval = () => {
    
    
    func();
    timer = setTimeout(interval, delay);
  };
  setTimeout(interval, delay);
  return {
    
    
    cancel: () => {
    
    
      clearTimeout(timer);
    },
  };
}

const {
    
     cancel } = mySetTimeout(() => console.log('999'), 1000);

setTimeout(() => {
    
    
  cancel();
}, 4000);

三. js对象转换为树结构

function arrayToTreeRec(nodes) {
    
    
  const map = {
    
    };
  const tree = [];
  for (const node of nodes) {
    
    
    node[node.id] = {
    
     ...node, children: [] };
  }
  for (const node of Object.values(map)) {
    
    
    if (node.parentId === null) {
    
    
      tree.push(node);
    } else {
    
    
      map[node.parentId].children.push(node);
    }
  }
  return tree;
}

四. 实现JSON.stringfy方法

function jsonStringify(obj) {
    
    
  // 处理非对象类型,直接返回对应的字符串形式
  if (typeof obj !== 'object' || obj === null) {
    
    
    // 处理字符串类型
    if (typeof obj === 'string') {
    
    
      console.log(obj);
      return '"' + obj + '"';
    }
    return String(obj);
  }

  // 处理数组类型
  if (Array.isArray(obj)) {
    
    
    const result = [];
    for (let i = 0; i < obj.length; i++) {
    
    
      result.push(jsonStringify(obj[i]));
    }
    return '[' + result.join(',') + ']';
  }

  // 处理对象类型
  const result = [];
  for (let key in obj) {
    
    
    if (obj.hasOwnProperty(key)) {
    
    
      const value = jsonStringify(obj[key]);
      // 处理 undefined、函数和 symbol 属性值
      if (value !== undefined) {
    
    
        const prop = '"' + key + '":' + value;
        result.push(prop);
      }
    }
  }
  return '{' + result.join(',') + '}';
}

let obj = {
    
    
  name: 'zs',
  age: 18,
  hobby: ['1', '2', '3']
}
console.log(jsonStringify(obj));

五. new操作符的实现

function _new(obj, ...rest){
    
    
  // 基于obj的原型创建一个新的对象
  const newObj = Object.create(obj.prototype);
  // 添加属性到新创建的newObj上, 并获取obj函数执行的结果.
  const result = obj.apply(newObj, rest);
  // 如果执行结果有返回值并且是一个对象, 返回执行的结果, 否则, 返回新创建的对象
  return typeof result === 'object' ? result : newObj;
}

六. 数组去重的几种方法

  1. 两层for循环
function unique(arr) {
    
    
  let len = arr.length
  for(let i = 0; i < len; i++) {
    
    
    for(let j = i + 1; j < len; j++) {
    
    
      if(arr[i] == arr[j]) {
    
    
        arr.splice(j, 1)
        j--
        len--
      }
    }
  }
  return arr
}
  1. filter + indexOf
function unique(arr) {
    
    
  return arr.filter((item, index) => {
    
    
    return arr.indexOf(item) == index
  })
}
  1. 创建新数组 + includes
function unique(arr) {
    
    
  let newArr = []
  for(let i = 0; i < arr.length; i++) {
    
    
    if(!newArr.includes(arr[i])) {
    
    
      newArr.push(arr[i])
    }
  }
  return newArr
}
  1. indexOf实现
function unique(arr) {
    
    
  let newArr = []
  for(let i = 0; i < arr.length; i++) {
    
    
    if(newArr.indexOf(arr[i]) === -1) {
    
    
      newArr.push(arr[i])
    }
  }
  return newArr
}
  1. Set实现
function unique(arr) {
    
    
  return [...new Set(arr)]
}

七. 大数相加

function add(str1, str2) {
    
    
  let maxLength = Math.max(str1.length, str2.length)
  str1 = str1.padStart(maxLength, 0)
  str2 = str2.padStart(maxLength, 0)
  let temp = 0
  let flag = 0 // 余数
  let result = ''
  for(let i = maxLength - 1; i >= 0; i--) {
    
    
    temp = str1[i] + str2[i] + flag
    flag = Math.floor(temp / 10)
    result = temp % 10 + result
  }
  if(flag == 1) {
    
    
    result = '1' + result
  }
  return result
}

let a = "9876543210123456789000000000123";
let b = "1234567898765432100000012345678901";
console.log(add(a, b));

八. 大数相乘

function multiplyStrings(num1, num2) {
    
    
  const len1 = num1.length;
  const len2 = num2.length;
  const result = new Array(len1 + len2).fill(0); // 结果数组初始化为0

  for (let i = len1 - 1; i >= 0; i--) {
    
    
    for (let j = len2 - 1; j >= 0; j--) {
    
    
      const product = Number(num1[i]) * Number(num2[j]); // 计算当前位的乘积
      const sum = result[i + j + 1] + product; // 当前位的和等于之前的结果加上当前位乘积

      result[i + j + 1] = sum % 10; // 保存当前位的数值
      result[i + j] += Math.floor(sum / 10); // 进位
    }
  }

  // 去掉结果前面的0
  while (result[0] === 0 && result.length > 1) {
    
    
    result.shift();
  }

  return result.join(''); // 将结果转为字符串返回
}

let a = "123";
let b = "456";
console.log(multiplyStrings(a, b));

猜你喜欢

转载自blog.csdn.net/qq_63299825/article/details/135955428