Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【面经】字节跳动 一面7(3):深度克隆 js 各种数据类型 #4

Open
liam61 opened this issue Mar 18, 2019 · 2 comments
Open
Labels
面经 面经

Comments

@liam61
Copy link
Owner

liam61 commented Mar 18, 2019

深度克隆 js 各种数据类型。附加题:实现对象中嵌套数组,数组中嵌套对象

JS 中基本类型

5 种原始类型:Boolean, Number, String, Null, Undefined(暂不考虑 ES6 的 Symbol)还有 Object

// 这里把数组也考虑了进来
function deepClone(someObj) {
  const { toString } = Object.prototype;
  const isObject = o => toString.call(o).slice(8, -1) === 'Object';

  function _deepClone(source) {
    if (Array.isArray(source)) { // 处理数组
      return source.reduce((res, item) => {
        res.push(_deepClone(item));
        return res;
      }, []);
    }

    if (isObject(source)) { // 处理对象
      return Object.keys(source).reduce((res, key) => {
        res[key] = _deepClone(source[key]);
        return res;
      }, {});
    }

    return source; // 处理其他类型
  }

  return _deepClone(someObj);
}

// 测试
console.log(deepClone([1, 2, [3], [4, 5, [6, 7]]]));
console.log(deepClone({ a: 1, b: { c: 3, d: 7, e: { y: 8, z: 4 } } }));
console.log(deepClone(12));
console.log(deepClone(true));
console.log(deepClone(null));
console.log(deepClone(undefined));
console.log(deepClone([1, { a: 9, b: 8 }, [3], [4, 5, [6, 7]]]));
console.log(deepClone({ a: 1, b: { c: [4, 5, [6]], d: 7, e: { y: 8, z: 4 } } }));
@liam61 liam61 added the 面经 面经 label Mar 18, 2019
@liam61 liam61 changed the title 【面经】字节跳动 二面9:实现简易版 MVVM 【面经】字节跳动 一面7(3):深度克隆任何基本类型 Mar 21, 2019
@LasyIsLazy
Copy link

“深度克隆任何基本类型”题目没有看明白,是指克隆常见的情况吗?如果是比较全面的深度克隆,还有几种情况需要考虑。

@liam61 liam61 closed this as completed Mar 21, 2019
@liam61 liam61 reopened this Mar 21, 2019
@liam61 liam61 closed this as completed Mar 21, 2019
@liam61 liam61 reopened this Mar 21, 2019
@liam61
Copy link
Owner Author

liam61 commented Mar 21, 2019

@LasyIsLazy 是的,考虑常见情况

@liam61 liam61 changed the title 【面经】字节跳动 一面7(3):深度克隆任何基本类型 【面经】字节跳动 一面7(3):深度克隆 js 各种数据类型 Mar 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
面经 面经
Projects
None yet
Development

No branches or pull requests

2 participants