ES6 - Some common methods added to objects

1,Object.is()

To compare whether two values ​​are equal in ES5, there are only two operators: equality operator ( ==) and strict equality operator ( ===)
, but they all have disadvantages, the former will be 自动转换data type, the latter NaNis not equal to itself, and +0equal to -0.

Let me talk about the comparison process of the two of them first:

双等号==

(1) If the two value types are the same, then compare three equal signs (===)

(2) If the two values ​​are of different types, they may also be equal. Type conversion and comparison must be performed according to the following rules: 1)
 
    If one is null and the other is undefined, then they are equal.
    2) If one is a string and the other is a value, put Strings are converted to numeric values ​​before comparison

三等号===:

(1) If the types are different, they must be unequal

(2) If both are numerical values ​​and are the same value, then they are equal; if at least one of them is NaN, then they are not equal.

(3) If both are strings and the characters in each position are the same, then they are equal, otherwise they are not equal.

(4) If both values ​​are true, or false, then equal

(5) If both values ​​refer to the same object or function, then they are equal, otherwise they are not equal

(6) If both values ​​are null, or undefined, then equal

ES6 proposes the "Same-value equality" algorithm to solve this problem. Object.isIt is a new way to deploy this algorithm. It is used to compare whether two values ​​are strictly equal, and the behavior of the strict comparison operator (===) is basically the same.

Object.is('123', '123')
// true
Object.is({
    
    }, {
    
    })
// false
Object.is([], [])
// false

Object.is()Determines whether two values ​​are the same. Two values ​​are the same if any of the following is true:

  • Both values ​​areundefined
  • Both values ​​arenull
  • Both values ​​are trueor bothfalse
  • Both values ​​are strings consisting of the same number of characters in the same order
  • Both values ​​point to the same object
  • Both values ​​are numbers and
    • are positive zero+0
    • are negative zero-0
    • are allNaN
    • NaNare all the same number except zero and

The following cases:

      console.log(111 == '111');// true 先转数子再比较是否一样
      
      // 1,判断 undefined 
      console.log(undefined === undefined);  // true
      console.log(Object.is(undefined, undefined)); // true

      // 2,判断 null 
      console.log(null === null); // true
      console.log(Object.is(null,null)); // true

      // 3,判断空数组[]
      console.log([] === []); // false
      console.log(Object.is([],[])); // false

      // 4,需要特别注意下 +0和-0
      console.log(+0 === -0); // true 显然是判断失误了
      console.log(Object.is(+0, -0)); //false

      // 5,判断NaN
      console.log(NaN === NaN); // false  显然也是判断失误了
      console.log(Object.is(NaN,NaN)); // true

It can be seen that using the Object.is() method will have higher accuracy.


2,Object.asign()

  • basic usage

Object.assign()The method is used for object merging, copying all enumerable properties of the source object (source) to the target object (target).

      // 目标对象 也可以是一个空对象
      const target = {
    
     name: 'Eula' };
      // 源对象 可以有多个
      const source1 = {
    
     age: 18 };
      const source2 = {
    
     friend: 'Amber' };

      Object.assign(target, source1, source2);
      console.log("target:",target); //{name: 'Eula', age: 18, friend: 'Amber'}

Object.assign()The first parameter of the method is the target object, and the following parameters are all source objects.

Note : If the target object and the source object have properties with the same name, or multiple source objects have properties with the same name, the later properties will override the previous properties, as follows:

      // 目标对象 
      const target = {
    
     name: 'Eula' }; // 这个会被覆盖掉
      // 源对象 
      const source1 = {
    
     age: 18 };
      const source2 = {
    
     name: 'Amber' };

      Object.assign(target, source1, source2);
      console.log("target:",target); //{name: 'Amber', age: 18}

Object.assign()The properties copied are limited, only the properties of the source object are copied (inherited properties are not copied), and non-enumerable properties are not copied ( enumerable: false).

     let copyA = Object.assign(
        {
    
     name: "Eula" },
        Object.defineProperty({
    
    }, "age", {
    
    
          enumerable: false, // 不可枚举
          value: 18 // 为此属性添加值 18 
        })
      );
      
      console.log("copyA:",copyA);//{ name: "Eula" }

In the above code, Object.assign()the object to be copied has only one non-enumerable property age, and this property has not been copied in. If you enumerable change to true, you can successfully copy;

  • Assign() method notes:

(1) shallow copy

Object.assign()method performs a shallow copy, not a deep copy. That is to say, if the value of a property of the source object is an object, then the copy of the target object gets a reference to this object.

      const obj1 = {
    
    my:{
    
     name: "Eula"} };
      const obj2 = Object.assign({
    
    }, obj1);
      // 改变源对象的属性
      obj1.my.name = "Amber"
      console.log(obj2); //{my: {name: 'Amber'}} 

Object.assign()What is copied is a reference to this object. Any changes to this object will be reflected on the target object.

(2) Replacement of attributes with the same name

For such nested objects, once an attribute with the same name is encountered, Object.assign()the only way to deal with it is to replace it, not to add it.

      const target = {
    
     my: {
    
     name: "Eula", age: 18 } };
      const source = {
    
     my: {
    
     name: "Amber" } };
      let res = Object.assign(target, source);
      console.log(res);// {my: {name: 'Amber'}}

The custom version provided by some function libraries Object.assign()(such as Lodash's _.defaultsDeep()method) can be merged with deep copy.


3,Object.getOwnPropertyDescriptors()

This method returns the description object of all the properties ( 非继承属性) of the specified object; as follows:

     const obj1 = {
    
    
        name: "Eula",
        fun: function () {
    
    
          return "优菈";
        }
      };
      const  Descriptors = Object.getOwnPropertyDescriptors(obj1)
      console.log("Descriptors:",Descriptors);

The printed results are as follows:
insert image description here


4,Object.setPrototypeOf()和getPrototypeOf()

  • setPrototypeOf()

Object.setPrototypeOfThe method is used to set the prototype object of an object; the following example is to add an attribute age to the obj prototype:

      let obj1 = {
    
     name: "Eula" };
      let obj2 = {
    
     age: 18 };
      // 下面是给obj1添加一个属性 name
      Object.setPrototypeOf(obj1, obj2);
      console.log(obj1.age); //18
  • getPrototypeOf()

This method is Object.setPrototypeOfmatched with the method and is used to read the prototype object of an object. The following is to read the new prototype attribute of obj1:

      let obj1 = {
    
     name: "Eula" };
      let obj2 = {
    
     age: 18 };
      // 下面是给obj1添加一个属性 name
      Object.setPrototypeOf(obj1, obj2);
      
      // 获取里面原型对象
      console.log(Object.getPrototypeOf(obj1)); //  { age: 18 }

5,Object.keys()、values() 和 entries()

(1) Object.keys()

Returns an array of all enumerable properties of self (not inherited) 键名.

      const ys = {
    
     KamisatoAyaka: '神里绫华', ShenliLingren: '神里绫人' };
      let ysKeys = Object.keys(ys)
      console.log(ysKeys); //  ['KamisatoAyaka', 'ShenliLingren'] 注意:只返回了对象每一项的键名

(2)Object.values()

Returns an array of all enumerable properties of self (not inherited) 键值.

      const ys = {
    
     KamisatoAyaka: '神里绫华', ShenliLingren: '神里绫人' };
      let ysvalues = Object.values(ys)
      console.log(ysvalues); // ['神里绫华', '神里绫人'] 注意:只返回了对象每一项的键值

(3)Object.entries()

Returns an array of all enumerable properties of the object itself (not inherited) 键值对.
Note: entries方法This object's is also returned 键值对, wrapped with an array.

      const ys = {
    
     KamisatoAyaka: "神里绫华", ShenliLingren: "神里绫人" };
      let ysentries = Object.entries(ys);
      console.log(ysentries);
      // 同时返回了键值对 并用一个数组包装
      //  ['KamisatoAyaka', '神里绫华']
      //  ['ShenliLingren', '神里绫人']

以下是配合for of 循环使用:

1, keys() is a traversal of key names

      let obj = {
    
    
        Amber: "安柏",
        Eula: "优菈",
        KamisatoAyaka: "神里绫华"
      };
	  // for of不支持遍历普通对象,可通过与Object.keys()搭配使用遍历
      for (let key of Object.keys(obj)) {
    
    
        console.log(key); // Amber,Eula,KamisatoAyaka  拿到的都是对象的键名
      }
      console.log(Object.keys(obj)); //(3) ['Amber', 'Eula', 'KamisatoAyaka']

2, values() is a traversal of key values

      let obj = {
    
    
        Amber: "安柏",
        Eula: "优菈",
        KamisatoAyaka: "神里绫华"
      };
      for (let key of Object.values(obj)) {
    
    
        console.log(key); // 安柏,优菈,神里绫华  拿到的都是对象的值
      }
      console.log(Object.values(obj)); //(3) ['安柏', '优菈', '神里绫华']

3. entries() is a traversal of key-value pairs

      let obj = {
    
    
        Amber: "安柏",
        Eula: "优菈",
        KamisatoAyaka: "神里绫华"
      };
      for (let key of Object.entries(obj)) {
    
    
        console.log(key);
        // ['Amber', '安柏']
        // ['Eula', '优菈']
        // ['KamisatoAyaka', '神里绫华']
      }

      console.log(Object.entries(obj));
      // 会以一个数组重新包装起来
      // [
      //   ["Amber", "安柏"],
      //   ["Eula", "优菈"],
      //   ["KamisatoAyaka", "神里绫华"]
      // ];

6,Object.fromEntries()

Object.fromEntries()The method is Object.entries()the inverse operation for converting an array of key-value pairs into an object.

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

The main purpose of this method is to restore the data structure of the key-value pair into an object, so it is especially suitable for converting Mapthe structure into an object.

// 例一
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

Object.fromEntries(entries)
// { foo: "bar", baz: 42 }

// 例二
const map = new Map().set('foo', true).set('bar', false);
Object.fromEntries(map)
// { foo: true, bar: false }

One use of this method is to cooperate with URLSearchParamsobjects to convert query strings into objects.

Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// { foo: "bar", baz: "qux" }

7,Object.hasOwn()

Object.hasOwn()It is used to judge whether it is its own attribute.

The properties of JavaScript objects are divided into two types: own properties and inherited properties. Object instances have a hasOwnProperty()method that can also determine whether a property is a native property.

Object.hasOwn()Two parameters can be accepted, the first is the object to be judged, and the second is the attribute name:

const foo = Object.create({
    
     a: 123 });
foo.b = 456;

Object.hasOwn(foo, 'a') // false
Object.hasOwn(foo, 'b') // true

In the above example, attribute a of object foo is an inherited attribute, and attribute b is a native attribute. Object.hasOwn()Returns for attribute a falseand returns for attribute b true.

Object.hasOwn()One advantage of is that no error will be reported for objects that do not inherit Object.prototype, but hasOwnProperty() will report an error.

const obj = Object.create(null);

obj.hasOwnProperty('foo') // 报错
Object.hasOwn(obj, 'foo') // false

In the above example, the object obj returned by Object.create(null) has no prototype and does not inherit any properties, which causes an error to be reported when calling obj.hasOwnProperty(), but Object.hasOwn() can handle this situation normally.

Guess you like

Origin blog.csdn.net/qq_43886365/article/details/132099297