【4】根据包名,在指定空间中创建对象

描述: 根据包名,在指定空间中创建对象

输入描述:namespace({a: {test: 1, b: 2}}, 'a.b.c.d')

输出描述:{a: {test: 1, b: {c: {d: {}}}}}

思想:递归(对象的嵌套参考数据结构中的树)

 1 function namespace(oNamespace, sPackage) {
 2     // 数组
 3     let arr = sPackage.split('.');
 4     // 深入的指针
 5     let pointer = oNamespace;
 6     // 遍历包
 7     for (let i = 0; i < arr.length; i++) {
 8         // 如果为undefined或者不是对象则赋值为空对象
 9         if (!pointer[arr[i]] || typeof pointer[arr[i]] !== 'object') {
10             pointer[arr[i]] = {};
11         }
12         // 指针深入该对象
13         pointer = pointer[arr[i]];
14     }
15     return oNamespace;
16 }
 1 function namespace(oNamespace, sPackage) {
 2     // 数组
 3     let arr = sPackage.split('.');
 4     // 深入的指针
 5     let pointer = oNamespace;
 6     // 遍历包
 7     for (let i = 0; i < arr.length; i++) {
 8         // 如果为undefined或者不是对象则赋值为空对象
 9         if (!pointer.hasOwnProperty(arr[i]) || Object.prototype.toString.call(pointer[arr[i]]) !== '[object Object]') {
10             pointer[arr[i]] = {};
11         }
12         // 指针深入该对象
13         pointer = pointer[arr[i]];
14     }
15     return oNamespace;
16 }

1. 判断对象的自身是否有某属性(hasOwnProperty)

2. hasOwnProperty / typeof / in / instanceof 的区别

(1)hasOwnProperty 是判断对象自身有没有某属性,不包含原型链的方法。

(2)in 是判断对象在自身和原型链上有没有该方法。

(3)instanceof 是判断对象在原型链上有没有该方法。

(4)typeof 判断操作数的类型,但是null也会判断为”object”

3.准确判断某值的类型

  • Object.prototype.toString.call(123) === “[object Number]”
  • Object.prototype.toString.call(‘aaa’) === “[object String]”
  • Object.prototype.toString.call(true) === “[object Boolean]”
  • Object.prototype.toString.call(undefined) === “[object Undefined]”
  • Object.prototype.toString.call(null) === ‘[object Null]’
  • Object.prototype.toString.call({}) === ‘[object Object]’
  • Object.prototype.toString.call([]) === ‘[object Array]’
  • Object.prototype.toString.call(Math) === “[object Math]”
  • Object.prototype.toString.call(new Date()) === “[object Date]”
  • Object.prototype.toString.call(new RegExp) === “[object RegExp]”
posted @ 2021-06-12 13:49  icyyyy  阅读(96)  评论(0)    收藏  举报