Object的操作方法

133 阅读1分钟
  • 通过Object下的Object.prototype.toString.call()方法来判断

Object.prototype.toString.call();

const isTypeOf = (data) => {
    return Object.prototype.toString.call(data)
}

isTypeOf({})  // "[object Object]"

isTypeOf([])  // "[object Array]"

isTypeOf(123) // "[object Number]"

isTypeOf('123') // "[object String]"

isTypeOf(null)  // "[object Null]"

isTypeOf() | isTypeOf(undefined)  // "[object Undefined]"

isTypeOf(function(){})  // "[object Function]"

isTypeOf(true) | isTypeOf(false)   // "[object Boolean]"

isTypeOf(/\w+/)  // "[object RegExp]"

isTypeOf(new Date())  // "[object Date]"


// 操作字符串  通过正则 截取自定的类型 并 转小写
//  
const isTypeOf2 = (data) => {
    return Object.prototype.toString.call(data).replace(/\[object (\w+)\]/, '$1').toLowerCase()
}

isTypeOf2([])  // "array"

isTypeOf2({}) // "object"

isTypeOf2(123) // "number"

isTypeOf2('123') // "string"

isTypeOf2(null)  // "null"

isTypeOf2() | isTypeOf(undefined)  // "undefined"

isTypeOf2(function(){})  // "function"

isTypeOf2(true) | isTypeOf(false)   // "boolean"

isTypeOf2(/\w+/)  // "regexp"

isTypeOf2(new Date())  // "date"
  • typeof

    • 可以判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);

    • 可以使用typeof判断变量是否存在(如if(typeof a!="undefined"){...});

    • Typeof 运算符的问题是无论引用的对象是什么类型 它都返回object

    typeof []    // "object"
    
    typeof {}    // "object"
    
    typeof function(){}   // "function"  
    
    typeof /\w+/   // "object"
    
    typeof null    // "object"
    
    typeof new Date()  // "object"
    
    typeof 123   //  "number"
        
    typeof '123'  //  "string"
    
    typeof true   // "boolean"
    
    typeof(null)   //  "object"
    
    typeof undefined  // "undefined"
    
    typeof function(){}  //  "function"
  • Object.freeze() 对象冻结

const obj1 = { age18name'法外狂徒' }

Object.freeze(obj1)  //  {age: 18, name: "法外狂徒"}

obj1.age = 21  // 21

obj   //   {age: 18, name: "法外狂徒"}

Object.freeze()的冻结是浅冻结
const obj2 = {
        zhangsan:{
           age:18,
           sex:'男'
        },
        love:'学习'
    }
    
Object.freeze(obj2)  

obj2.zhangsan.age =  20
obj2.zhangsan.age  // 20 深层的对象 未被冻结

obj2.love = '打游戏' 
obj2.love  //  学习  单层的对象被冻结了

使用递归调用的思想可以实现一个深度冻结的函数
function deepFreeze(obj) {
  const propNames = Object.getOwnPropertyNames(obj)
  propNames.forEach(function(name) {
    const prop = obj[name]
    if (typeof prop == 'object' && prop !== null)
      deepFreeze(prop)
  })
  return Object.freeze(obj);
}
  • Object.isFrozen() 判断object是否被冻结
const obj1 = { age18name'法外狂徒' }

Object.isFrozen(obj1)  // false

Object.isFrozen()  // true

Object.freeze(obj1)  // 冻结  {age: 18, name: "法外狂徒"}

Object.isFrozen(obj1)   // true