前端面试-手撕代码

翻转字符串

思路:先将字符串变成数组,再利用数组相关的处理处理函数实现最终目的。

实现:

//翻转字符串
let str = '123'

let str2 = str.split('').reverse().join('')

let str3 = [...str].reverse().join('')

let str4_arr = []
for (let i = str.length - 1; i >= 0; i--) {
  str4_arr.push(str[i])
}
let str4 = str4_arr.join('')

let str5 = str.split('').reduce((pre, cur) => {
  return cur + pre
}, '')
console.log(str2, str3, str4, str5)

对象深浅拷贝 

实现:

function deepClone1(obj){
  let newObj = Array.isArray(obj) ? [] : {}
  for(let key in obj){
    newObj[key] = obj[key]
  }
  return newObj
}


function deepClone2(obj){
  return JSON.parse(JSON.stringify(obj))
}


function deepClone3(obj){
  if(obj === null || typeof obj !== 'object'){
    return obj
  }
  let newObj = Array.isArray(obj) ? [] : {}
  for(let key in obj){
    if(typeof obj[key] === 'object'){
      newObj[key] = deepClone3(obj[key])
    }else{
      newObj[key] = obj[key]
    }
  }
  return newObj
}


function deepClone4(obj){
  if(obj === null || typeof obj !== 'object' || obj instanceof RegExp || obj instanceof Date){
    return obj
  }
  let newObj = Array.isArray(obj) ? [] : {}
  for(let key in obj){
    newObj[key] = deepClone4(obj[key])
  }
  return newObj
}



function deepClone5(obj){
  let newObj = Object.assign({},obj)
  return newObj
}


function deepClone6(obj){
  let newObj = lodash.cloneDeep(obj)
  return newObj
}



function deepClone7(data, hash = new WeakMap()) {
  if(typeof data !== 'object' || data === null){
    throw new TypeError('传入参数不是对象')
  }
  // 判断传入的待拷贝对象的引用是否存在于hash中
  if(hash.has(data)) {
    return hash.get(data)
  }
  let newData = {};
  const dataKeys = Object.keys(data);
  dataKeys.forEach(value => {
    const currentDataValue = data[value];
    // 基本数据类型的值和函数直接赋值拷贝 
    if (typeof currentDataValue !== "object" || currentDataValue === null) {
      newData[value] = currentDataValue;
    } else if (Array.isArray(currentDataValue)) {
      // 实现数组的深拷贝
      newData[value] = [...currentDataValue];
    } else if (currentDataValue instanceof Set) {
      // 实现set数据的深拷贝
      newData[value] = new Set([...currentDataValue]);
    } else if (currentDataValue instanceof Map) {
      // 实现map数据的深拷贝
      newData[value] = new Map([...currentDataValue]);
    } else { 
      // 将这个待拷贝对象的引用存于hash中
      hash.set(data,data)
      // 普通对象则递归赋值
      newData[value] = deepClone7(currentDataValue, hash);
    } 
  }); 
  return newData;
}


function deepClone8(obj){
  let newObj = {...obj}
  return newObj
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值