蔚来面试代码题

  1. list转树
function filterArray(data, parent) {

  var tree = [];
  var temp;
  for (var i = 0; i < data.length; i++) {
    if (data[i].parent == parent) {
      var obj = data[i];
      temp = filterArray(data, data[i].id);
      if (temp.length > 0) {
        obj.subs = temp;
      }
      tree.push(obj);
    }
  }
  return tree;
}
  1. promise基本实现

  2. deepClone


function isObject(obj) {
	return typeof obj === 'object' && obj != null;
}
function cloneDeep(source) {
    if (!isObject(source)) return source; // 非对象返回自身
      
    var target = Array.isArray(source) ? [] : {};
    for(var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
            if (isObject(source[key])) {
                target[key] = cloneDeep2(source[key]); // 注意这里
            } else {
                target[key] = source[key];
            }
        }
    }
    return target;
}

// 使用上面测试用例测试一下
var b = cloneDeep(a);
console.log(b);
// { 
//   name: 'muyiy', 
//   book: { title: 'You Don\'t Know JS', price: '45' },
//   a1: undefined,
//   a2: null,
//   a3: 123
// }

上面日期正则的会有问题,使用下面的方式

function cloneDeep (obj){
  // 1.判断是否为null 或undefined
  if (typeof obj == null ) return obj;
  // 2.判断是否为日期Date
  if (obj instanceof Date) return new Date(obj);
  // 3.判断是否为正则 typeof /\d+/ === 'object'
  if (obj instanceof RegExp) return new RegExp(obj);
  // 4.如果不是数组或对象,返回该值
  if (typeof obj !== 'object') return obj;
  // 接下来,要么是对象,要么是数组 可以用 new obj.constructor得到它类型的空值
  let cloneObj = new obj.constructor;
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 递归深拷贝
      cloneObj[key] = cloneDeep(obj[key]);
    }
  }
  return cloneObj;
}

function deepClone(obj) {
    let copy = Object.create(Object.getPrototypeOf(obj));
    let propertyNames = Object.getOwnPropertyNames(obj);
    propertyNames.forEach(function (items) {
        let item = Object.getOwnPropertyDescriptor(obj, items);
        Object.defineProperty(copy, items, item);

    });
    return copy;
}
let obj = {
    name:'lily',
    arr:[1,2,3],
    date: [new Date(1536627600000), new Date(1540047600000)],
    RegExp: new RegExp('\\w+'),
    job:undefined,
    obj2:{
        fun:function(){}
    }
};
let testObj = deepClone(obj);
testObj.name = '不知火舞';
console.log(obj);   //{ name: 'lily',
                    // arr: [ 1, 2, 3 ],
                    // date: [ 2018-09-11T01:00:00.000Z, 2018-10-20T15:00:00.000Z ],
                    // RegExp: /\w+/,
                    // job: undefined,
                    // obj2: { fun: [Function: fun] } }
console.log(testObj)   //{ name: '不知火舞',
                        // arr: [ 1, 2, 3 ],
                        // date: [ 2018-09-11T01:00:00.000Z, 2018-10-20T15:00:00.000Z ],
                        // RegExp: /\w+/,
                        // job: undefined,
                        // obj2: { fun: [Function: fun] } }


posted @ 2022-03-04 16:06  小猪ab  阅读(318)  评论(0编辑  收藏  举报