newPromise / js-

0 stars 0 forks source link

复制对象 #26

Open newPromise opened 6 years ago

newPromise commented 6 years ago

使用 clone 用来复制对象或者用来复制数组

@params {Object}  传入的对象
@description 用来克隆对象或者数组
@return 如果是对象或者数组那么返回被克隆的对象,如果非对象,那么返回原来的值

function  clone (obj) {
  if (typeof obj === 'Object' &&  typeof  obj !== 'null') {
    let o = Object.prototype.toString.call(obj).slice(8, -1) === "Array" ? [] : {};
    for  (let i in  obj) {
        if (typeof obj[i] === 'Object'  &&  typeof   @obj[i]!== 'null') {
          o[i] = clone(obj[i]);
       } else {
          o[i] = obj[i];
       }
    } else {
      return obj;  
}
return o;
}

使用 typeof 用来判断数据类型, 可以使用 typeof 进行判断的类型 : Object Number String Undefined Function String.slice() 方法用来截取字符串:

String.slice(beginSlice, endSlice); 当 endSlice 小于零的时候,截取字符串从 beginSlice 到 endSlice + length 的位置

newPromise commented 6 years ago

上面的代码存在错误,主要是因为 使用 typeOf 判断值为 null的时候: typeOf null === 'Object' 对于 null 类型进行检测,检测到的是 object

newPromise commented 6 years ago
function clone(obj) {
  if (typeof obj === 'object' && obj) {
    let o = Object.prototype.toString.call(oj).slice(8, -1) === 'Array' ? [] : {};
    for (let props in obj) {
        if (typeof obj[props] === 'object' && obj[props]) {
                o[props] = clone(obj[props]);
            } else {
                o[props] = obj[props];
            }
        }
        return o;
    } else {
        return obj
    }
}
newPromise commented 6 years ago

关于使用 null

nulljavascript 中被认为是表示一个空值,或者说表明一个值的类型为空 typeof null : Object 对于 null 值执行 typeof 操作结果为 Object 这是一个 bug 解决办法:

判断 obj 是否是 `null` 值
(typeof obj === 'Object' && !obj) // true

undefined 的区别

使用 undefined 表明这个值没有被声明

var a;
typeof a // undefined

var a = null;
typeof a // Object

undefined 和 null 都是假值, 可以被强制布尔值转换为 false

js 中的假值还有: undefined null false +0 -0 NaN 以及 "" 因此:

undefined == null // true
因为使用 undefined 和 null 都会被强制类型转换为 false, 使用 `==` 会执行强制类型转换, 使用 `===` 仅仅是进行比较值是否要相等

undefined === null // false

如上