JSCoding

作者: Mrzhangy | 来源:发表于2021-08-07 18:46 被阅读0次

    大数相加

    const numAdd = (a, b) => {
      // 字符串转换
      a = '0' + a;
      b = '0' + b;
      const len = Math.max(a.length, b.length);
      // 统一长度
      a = a.padStart(len, '0');
      b = b.padStart(len, '0');
     
      let temp = 0;
      let jw = 0; // 进位
      let res = [];
      for (let i = len - 1; i >= 0; i--) {
        temp = Number(a[i]) + Number(b[i]) + jw;
        if (temp >= 10) {
          jw = 1;
          res.unshift((temp + '')[1]);
        } else {
          jw = 0;
          res.unshift(temp);
        }
      }
      return res.join('').replace(/^0/, '');
    }
    

    深拷贝

    const deepCopy = (obj) => {
      let res;
      if (typeof obj === 'object') {
        for (let i in obj) {
          res[i] = typeof obj[i] === 'object' ? deepCopy(obj[i]) : obj[i];
        }
      } else {
        res = obj;
      }
      return res;
    }
    

    相关文章

      网友评论

          本文标题:JSCoding

          本文链接:https://www.haomeiwen.com/subject/sqegvltx.html