Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Abstract

ES6, short for ECMAScript 6.0, is the next generation standard of the JavaScript language. The relationship between ECMAScript and JavaScript is that the former is a specification of the latter and the latter is an implementation of the former.

Object to add a method

Object.is()

Problem solved: ES5 has only two operators for comparing whether two values are equal: == and ===.

== automatically converts the data type

let a = '1' + 1
console.log(a) / / "11"
Copy the code

NaN of === = is not equal to itself, plus 0 is minus 0

Usage:

Object.is(+0, -0)
object.is(NaN.NaN)
Copy the code

object.assign()

Object.assign(target, source1, source2…) Method is used to merge objects, copy all the enumerable properties of the source object to the target object.

const target = { a: 1 }
const source1 = { b: 2 }
const source2 = { c: 3 }

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

Note:

  • Parameters that are not objects are first converted to objects
  • If the first argument isnullundefinedAnd complains
/ / an error
Object.assign(null)
Object.assign(undefined)

/ / is not an error
Object.assign(a: 1.null)
Object.assign(a: 1.undefined)
Copy the code
  • Object.assign()Is a shallow copy. If a property value of the source object is an object, the target object is copied with a reference to the object.
  • Properties of the same name are replaced
const target = { a: { b: 'c'.d: 'e'}}const source = { a: { b: 'hello'}}Object.assign(target, source)
// { a: { b: 'hello' } }
Copy the code

Object.getOwnPropertyDescriptors()

__proto__ attributes, Object.setProtoTypeof (), Object.getPrototypeof ()

Object.keys()

Returns an array of the key names of all the Enumerable properties of the parameter object itself (excluding inheritance).

let obj = { foo: 'bar'.baz: 42 }
Object.keys(obj)
// ["foo", "baz"]
Copy the code

Object.values()

Returns an array of all the key values of an Enumerable property of the parameter object itself (not including inheritance).

let obj = { foo: 'bar'.baz: 42 }
Object.values(obj)
// ["bar", 42]
Copy the code

Object.entries()

Returns an array of all of the key/value pairs of the parameter object’s own (not inherited) enumerable properties.

let obj = { foo: 'bar'.baz: 42 }
Object.entries(obj)
// [["foo", "bar"], ["baz", 42]]
Copy the code

Object.fromEntries()

The inverse operation of Object.entries() to turn an array of key-value pairs into objects.

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