[TOC] #### 1. Object.assign() --- Object.assign() 用于將所有可枚舉屬性的值從一個(gè)或多個(gè)源對(duì)象復(fù)制到目標(biāo)對(duì)象,并返回目標(biāo)對(duì)象 通俗來講,就是用于將一個(gè)或多個(gè)對(duì)象合并到目標(biāo)對(duì)象。這也是實(shí)際開發(fā)中使用最多的場(chǎng)景 下面是將 user2 合并到 user1 對(duì)象中,并且返回值是合并后的結(jié)果 ```javascript const user1 = { name: 'liang' } const user2 = { age: 20, likes: ['html', 'css'] } Object.assign(user1, user2) console.log(user1) // {"name":"liang","age":20,"likes":["html","css"]} ``` 如果目標(biāo)對(duì)象和源對(duì)象有同名屬性,則后面的屬性會(huì)覆蓋前面的屬性 ```javascript const user1 = { name: 'liang' } const user2 = { name: 'wang', age: 24 } Object.assign(user1, user2) console.log(user1) // {"name":"wang","age":24} ``` Object.assign() 合并對(duì)象是淺拷貝,而非深拷貝 淺拷貝只會(huì)拷貝對(duì)象的第一層屬性,如果這些屬性是對(duì)象,則不會(huì)對(duì)這些對(duì)象進(jìn)行拷貝,而是直接復(fù)制對(duì)象的引用。這意味著,對(duì)于淺拷貝后的對(duì)象,如果原對(duì)象的屬性值發(fā)生了變化,淺拷貝后的對(duì)象的屬性值也會(huì)跟著發(fā)生變化 ```javascript const user1 = { name: 'liang' } const user2 = { likes: ['html', 'css'] } Object.assign(user1, user2) user2.likes.push('js') console.log(user1) // {"name":"liang","likes":["html","css","js"]} ``` 合并對(duì)象但是不希望改變目標(biāo)對(duì)象原本的值,可以這樣寫 : ```javascript const user1 = { name: 'liang' } const user2 = { age: 24, height: 180 } const merge = Object.assign({}, user1, user2) console.log(merge) // {"name":"liang","age":24,"height":180} ``` #### 2. Object.keys() --- Object.keys() 用于獲取對(duì)象的鍵名,并且返回一個(gè)包含所有鍵名的數(shù)組 ```javascript const user = { name: 'liang', age: 24, height: '180cm' } const array = Object.keys(user) console.log(array) // ["name","age","height"] ``` JS 的 Object.keys() 方法類似于 PHP 函數(shù) array_keys() ```php array_keys(array) ``` #### 3. Object.values() --- Object.keys() 用于獲取對(duì)象的鍵值,并且返回一個(gè)包含所有鍵值的數(shù)組 ```javascript const user = { name: 'liang', age: 24, height: '180cm' } const array = Object.values(user) console.log(array) // ["liang",24,"180cm"] ``` JS 的 Object.keys() 方法類似于 PHP 函數(shù) array_keys() ```php array_values(array) ``` #### 4. Object.entries() --- Object.keys() 返回一個(gè)包含所有鍵值對(duì)的數(shù)組 ```javascript const user = { name: 'liang', age: 24, height: '180cm' } const array = Object.entries(user) console.log(array) // [["name","liang"],["age",24],["height","180cm"]] ``` #### 5. Object.is() --- Object.is() 用來比較兩個(gè)值是否嚴(yán)格相等,和嚴(yán)格比較運(yùn)算符 (===) 基本一致 Object.is() 和嚴(yán)格比較運(yùn)算符 (===) 的不同之處有兩個(gè): `0 和 -0`、`NaN 等于自身`,其他情況下作用完全相同 ```javascript console.log(0 === -0) // true console.log(Object.is(0, -0)) // false console.log(NaN === NaN) // false console.log(Object.is(NaN, NaN)) // true ```