对象的新增方法(es6)

268 阅读2分钟

ES6总结系列之 对象的新增方法 篇


1. Object.is() --比较两个值是否相等

Same-value equality(同值相等) Object.is()与严格相等(===)的不同只有两处:

  1. +0不等于-0
Object.is(+0, -0)    //false
+0 === -0         //true
  1. NaN等于自身
Object.is(NaN, NaN)   //true
NaN === NaN        //false

2. Object.assign() --合并对象

①Object.assign(target, source1, source2) ②将源对象合并到目标对象,并返回目标对象

const target = { a: 1 };

const source1 = { b: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

③注意事项: 1)浅拷贝,且只拷贝自身属性不拷贝继承的,symbol值也会被拷贝 2)只拷贝可枚举对象属性,当非首参数是(数值,字符串,布尔值)时,只有字符串会以数组的形式生效,因为只有字符串的包装对象,会产生可枚举属性

Object(true) // {[[PrimitiveValue]]: true}
Object(10)  //  {[[PrimitiveValue]]: 10}
Object('abc') // {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

3)同名属性后面会覆盖前面 4)参数如果不是对象,就先转化为对象

typeof Object.assign(2) // "object"

5)首参数不能为null和undefined,因为无法转化为对象,会报错

Object.assign(undefined) // 报错
Object.assign(null) // 报错

6)非首参数如果是null和undefined,就会跳过,不会报错

3.Object.getOwnPropertyDescriptors() --返回自身属性的描述 对象

ES5 的Object.getOwnPropertyDescriptor(obj, key)方法会返回某个对象属性的描述对象 ES2017引入了 Object.getOwnPropertyDescriptors(obj) 返回自身属性的描述 对象

const obj = {
  foo: 123,
  get bar() { return 'abc' }
};

Object.getOwnPropertyDescriptors(obj)
// { foo:
//    { value: 123,
//      writable: true,
//      enumerable: true,
//      configurable: true },
//   bar:
//    { get: [Function: get bar],
//      set: undefined,
//      enumerable: true,
//      configurable: true } 
// }

4.__proto__属性,Object.setPrototypeOf(),Object.getPrototypeOf()

Object.setPrototypeOf(object, prototype)

①用来设置一个对象的原型对象(prototype),返回对象本身 ②第一个参数如果不是对象,会转化为对象,由于返回的是第一个参数本身,所以数值,字符串,布尔值这个操作不会产生任何效果

Object.setPrototypeOf(1, {}) === 1 // true
Object.setPrototypeOf('foo', {}) === 'foo' // true
Object.setPrototypeOf(true, {}) === true // true

④undefined和null无法转为对象,所以如果第一个参数是undefined或null,就会报错。

Object.getPrototypeOf()

①Object.getPrototypeOf(obj),读取一个对象的原型对象

5.对象的遍历

Object.keys(obj)

①返回一个数组,由键名组成(自身,可枚举属性键名)

Object.values(obj)

①返回一个数组,由键值组成(自身,可枚举属性键值)

Object.entries(obj)

①返回一个数组,由键值对组成(自身,可枚举属性)

Object.fromEntries(arr)

Object.entries(o)的逆操作,将键值对数组转化为对象

Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }