ES5 比較兩個(gè)值是否相等,只有兩個(gè)運(yùn)算符:相等運(yùn)算符
( == )和嚴(yán)格相等運(yùn)算符
( === )。它們都有缺點(diǎn),前者會(huì)自動(dòng)轉(zhuǎn)換數(shù)據(jù)類型,后者的 NaN 不等于自身,以及 +0 等于 -0 。JavaScript 缺乏一種運(yùn)算,在所有環(huán)境中,只要兩個(gè)值是一樣的,它們就應(yīng)該相等。
ES6 提出“Same-value equality”
(同值相等)算法,用來(lái)解決這個(gè)問(wèn)題。Object.is
就是部署這個(gè)算法的新方法。它用來(lái)比較兩個(gè)值是否嚴(yán)格相等,與嚴(yán)格比較運(yùn)算符(===)的行為基本一致。
Object.is('foo', 'foo')
// true
Object.is({}, {})
// false
不同之處只有兩個(gè):一是 +0 不等于 -0 ,二是 NaN 等于自身。
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
ES5 可以通過(guò)下面的代碼,部署 Object.is 。
Object.defineProperty(Object, 'is', {
value: function(x, y) {
if (x === y) {
// 針對(duì)+0 不等于 -0的情況
return x !== 0 || 1 / x === 1 / y;
}
// 針對(duì)NaN的情況
return x !== x && y !== y;
},
configurable: true,
enumerable: false,
writable: true
});
Object.assign
方法用于對(duì)象的合并,將源對(duì)象
(source)的所有可枚舉
屬性,復(fù)制到目標(biāo)對(duì)象(target)。
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
Object.assign 方法的第一個(gè)參數(shù)是目標(biāo)對(duì)象,后面的參數(shù)都是源對(duì)象。
注意,如果目標(biāo)對(duì)象與源對(duì)象有同名屬性,或多個(gè)源對(duì)象有同名屬性,則后面的屬性會(huì)覆蓋前面的屬性。
const target = { a: 1, b: 1 };
const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
如果只有一個(gè)參數(shù),Object.assign
會(huì)直接返回該參數(shù)。
const obj = {a: 1};
Object.assign(obj) === obj // true
如果該參數(shù)不是對(duì)象,則會(huì)先轉(zhuǎn)成對(duì)象,然后返回。
typeof Object.assign(2) // "object"
由于 undefined 和 null 無(wú)法轉(zhuǎn)成對(duì)象,所以如果它們作為參數(shù),就會(huì)報(bào)錯(cuò)。
Object.assign(undefined) // 報(bào)錯(cuò)
Object.assign(null) // 報(bào)錯(cuò)
如果非對(duì)象參數(shù)出現(xiàn)在源對(duì)象的位置(即非首參數(shù)),那么處理規(guī)則有所不同。首先,這些參數(shù)都會(huì)轉(zhuǎn)成對(duì)象,如果無(wú)法轉(zhuǎn)成對(duì)象,就會(huì)跳過(guò)。這意味著,如果 undefined 和 null 不在首參數(shù),就不會(huì)報(bào)錯(cuò)。
let obj = {a: 1};
Object.assign(obj, undefined) === obj // true
Object.assign(obj, null) === obj // true
其他類型的值(即數(shù)值、字符串和布爾值)不在首參數(shù),也不會(huì)報(bào)錯(cuò)。但是,除了字符串會(huì)以數(shù)組形式,拷貝入目標(biāo)對(duì)象,其他值都不會(huì)產(chǎn)生效果。
const v1 = 'abc';
const v2 = true;
const v3 = 10;
const obj = Object.assign({}, v1, v2, v3);
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
上面代碼中, v1 、 v2 、 v3 分別是字符串、布爾值和數(shù)值,結(jié)果只有字符串合入目標(biāo)對(duì)象(以字符數(shù)組的形式),數(shù)值和布爾值都會(huì)被忽略。這是因?yàn)橹挥凶址陌b對(duì)象,會(huì)產(chǎn)生可枚舉屬性。
Object(true) // {[[PrimitiveValue]]: true}
Object(10) // {[[PrimitiveValue]]: 10}
Object('abc') // {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}
上面代碼中,布爾值、數(shù)值、字符串分別轉(zhuǎn)成對(duì)應(yīng)的包裝對(duì)象,可以看到它們的原始值都在包裝對(duì)象的內(nèi)部屬性
[[PrimitiveValue]] 上面,這個(gè)屬性是不會(huì)被 Object.assign 拷貝的。只有字符串的包裝對(duì)象,會(huì)產(chǎn)生可枚舉的實(shí)義屬性,那些屬性則會(huì)被拷貝。
Object.assign 拷貝的屬性是有限制的,只拷貝源對(duì)象的自身屬性(不拷貝繼承屬性),也不拷貝不可枚舉
的屬性( enumerable: false )。
Object.assign({b: 'c'},
Object.defineProperty({}, 'invisible', {
enumerable: false,
value: 'hello'
})
)
// { b: 'c' }
上面代碼中, Object.assign
要拷貝的對(duì)象只有一個(gè)不可枚舉屬性
invisible ,這個(gè)屬性并沒(méi)有被拷貝進(jìn)去。
屬性名為 Symbol 值的屬性,也會(huì)被 Object.assign 拷貝。
Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' })
// { a: 'b', Symbol(c): 'd' }
(1)淺拷貝
Object.assign
方法實(shí)行的是淺拷貝
,而不是深拷貝。也就是說(shuō),如果源對(duì)象某個(gè)屬性的值是對(duì)象,那么目標(biāo)對(duì)象拷貝得到的是這個(gè)對(duì)象的引用。
const obj1 = {a: {b: 1}};
const obj2 = Object.assign({}, obj1);
obj1.a.b = 2;
obj2.a.b // 2
上面代碼中,源對(duì)象 obj1 的 a 屬性的值是一個(gè)對(duì)象, Object.assign 拷貝得到的是這個(gè)對(duì)象的引用。這個(gè)對(duì)象的任何變化,都會(huì)反映到目標(biāo)對(duì)象上面。
(2)同名屬性的替換
對(duì)于這種嵌套的對(duì)象,一旦遇到同名屬性, Object.assign 的處理方法是替換,而不是添加。
const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)
// { a: { b: 'hello' } }
上面代碼中, target 對(duì)象的 a 屬性被 source 對(duì)象的 a 屬性整個(gè)替換掉了,而不會(huì)得到 { a: { b: 'hello', d: 'e' } } 的結(jié)果。這通常不是開發(fā)者想要的,需要特別小心。
一些函數(shù)庫(kù)提供 Object.assign 的定制版本(比如 Lodash 的 _.defaultsDeep 方法),可以得到深拷貝的合并。
(3)數(shù)組的處理
Object.assign
可以用來(lái)處理數(shù)組
,但是會(huì)把數(shù)組視為對(duì)象。
Object.assign([1, 2, 3], [4, 5])
// [4, 5, 3]
上面代碼中, Object.assign 把數(shù)組視為屬性名為 0、1、2 的對(duì)象,因此源數(shù)組的 0 號(hào)屬性 4 覆蓋了目標(biāo)數(shù)組的 0 號(hào)屬性 1 。
(4)取值函數(shù)的處理
Object.assign
只能進(jìn)行值的復(fù)制
,如果要復(fù)制的值是一個(gè)取值函數(shù),那么將求值后再?gòu)?fù)制。
const source = {
get foo() { return 1 }
};
const target = {};
Object.assign(target, source)
// { foo: 1 }
上面代碼中, source 對(duì)象的 foo 屬性是一個(gè)取值函數(shù), Object.assign 不會(huì)復(fù)制這個(gè)取值函數(shù),只會(huì)拿到值以后,將這個(gè)值復(fù)制過(guò)去。
Object.assign 方法有很多用處。
(1)為對(duì)象添加屬性
class Point {
constructor(x, y) {
Object.assign(this, {x, y});
}
}
上面方法通過(guò) Object.assign 方法,將 x 屬性和 y 屬性添加到 Point 類的對(duì)象實(shí)例。
(2)為對(duì)象添加方法
Object.assign(SomeClass.prototype, {
someMethod(arg1, arg2) {
···
},
anotherMethod() {
···
}
});
// 等同于下面的寫法
SomeClass.prototype.someMethod = function (arg1, arg2) {
···
};
SomeClass.prototype.anotherMethod = function () {
···
};
上面代碼使用了對(duì)象屬性的簡(jiǎn)潔表示法,直接將兩個(gè)函數(shù)放在大括號(hào)中,再使用 assign 方法添加到 SomeClass.prototype 之中。
(3)克隆對(duì)象
function clone(origin) {
return Object.assign({}, origin);
}
上面代碼將原始對(duì)象拷貝到一個(gè)空對(duì)象,就得到了原始對(duì)象的克隆。
不過(guò),采用這種方法克隆,只能克隆原始對(duì)象自身的值,不能克隆它繼承的值。如果想要保持繼承鏈,可以采用下面的代碼。
function clone(origin) {
let originProto = Object.getPrototypeOf(origin);
return Object.assign(Object.create(originProto), origin);
}
(4)合并多個(gè)對(duì)象
將多個(gè)對(duì)象合并到某個(gè)對(duì)象。
const merge =
(target, ...sources) => Object.assign(target, ...sources);
如果希望合并后返回一個(gè)新對(duì)象,可以改寫上面函數(shù),對(duì)一個(gè)空對(duì)象合并。
const merge =
(...sources) => Object.assign({}, ...sources);
(5)為屬性指定默認(rèn)值
const DEFAULTS = {
logLevel: 0,
outputFormat: 'html'
};
function processContent(options) {
options = Object.assign({}, DEFAULTS, options);
console.log(options);
// ...
}
上面代碼中, DEFAULTS 對(duì)象是默認(rèn)值, options 對(duì)象是用戶提供的參數(shù)。 Object.assign 方法將 DEFAULTS 和 options 合并成一個(gè)新對(duì)象,如果兩者有同名屬性,則 options 的屬性值會(huì)覆蓋 DEFAULTS 的屬性值。
注意,由于存在淺拷貝的問(wèn)題, DEFAULTS 對(duì)象和 options 對(duì)象的所有屬性的值,最好都是簡(jiǎn)單類型,不要指向另一個(gè)對(duì)象。否則, DEFAULTS 對(duì)象的該屬性很可能不起作用。
const DEFAULTS = {
url: {
host: 'example.com',
port: 7070
},
};
processContent({ url: {port: 8000} })
// {
// url: {port: 8000}
// }
上面代碼的原意是將 url.port 改成 8000, url.host 不變。實(shí)際結(jié)果卻是 options.url 覆蓋掉 DEFAULTS.url ,所以 url.host 就不存在了。
ES5 的 Object.getOwnPropertyDescriptor()
方法會(huì)返回某個(gè)對(duì)象屬性的描述對(duì)象
(descriptor)。ES2017 引入了Object.getOwnPropertyDescriptors()
方法,返回指定對(duì)象所有自身屬性
(非繼承屬性)的描述對(duì)象。
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 } }
上面代碼中,Object.getOwnPropertyDescriptors()
方法返回一個(gè)對(duì)象
,所有原對(duì)象的屬性名都是該對(duì)象的屬性名,對(duì)應(yīng)的屬性值就是該屬性的描述對(duì)象。
該方法的實(shí)現(xiàn)非常容易。
function getOwnPropertyDescriptors(obj) {
const result = {};
for (let key of Reflect.ownKeys(obj)) {
result[key] = Object.getOwnPropertyDescriptor(obj, key);
}
return result;
}
該方法的引入目的,主要是為了解決 Object.assign() 無(wú)法正確拷貝 get 屬性和 set 屬性的問(wèn)題。
const source = {
set foo(value) {
console.log(value);
}
};
const target1 = {};
Object.assign(target1, source);
Object.getOwnPropertyDescriptor(target1, 'foo')
// { value: undefined,
// writable: true,
// enumerable: true,
// configurable: true }
上面代碼中, source
對(duì)象的 foo
屬性的值是一個(gè)賦值函數(shù)
, Object.assign 方法將這個(gè)屬性拷貝給 target1 對(duì)象,結(jié)果該屬性的值變成了 undefined 。這是因?yàn)?Object.assign 方法總是拷貝一個(gè)屬性的值,而不會(huì)拷貝它背后的賦值方法或取值方法。
這時(shí), Object.getOwnPropertyDescriptors() 方法配合 Object.defineProperties() 方法,就可以實(shí)現(xiàn)正確拷貝。
const source = {
set foo(value) {
console.log(value);
}
};
const target2 = {};
Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source));
Object.getOwnPropertyDescriptor(target2, 'foo')
// { get: undefined,
// set: [Function: set foo],
// enumerable: true,
// configurable: true }
上面代碼中,兩個(gè)對(duì)象合并的邏輯可以寫成一個(gè)函數(shù)。
const shallowMerge = (target, source) => Object.defineProperties(
target,
Object.getOwnPropertyDescriptors(source)
);
Object.getOwnPropertyDescriptors() 方法的另一個(gè)用處,是配合 Object.create() 方法,將對(duì)象屬性克隆到一個(gè)新對(duì)象。這屬于淺拷貝。
const clone = Object.create(Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj));
// 或者
const shallowClone = (obj) => Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
上面代碼會(huì)克隆對(duì)象 obj 。
另外, Object.getOwnPropertyDescriptors() 方法可以實(shí)現(xiàn)一個(gè)對(duì)象繼承另一個(gè)對(duì)象。以前,繼承另一個(gè)對(duì)象,常常寫成下面這樣。
const obj = {
__proto__: prot,
foo: 123,
};
ES6 規(guī)定 proto 只有瀏覽器要部署,其他環(huán)境不用部署。如果去除 proto ,上面代碼就要改成下面這樣。
const obj = Object.create(prot);
obj.foo = 123;
// 或者
const obj = Object.assign(
Object.create(prot),
{
foo: 123,
}
);
有了 Object.getOwnPropertyDescriptors() ,我們就有了另一種寫法。
const obj = Object.create(
prot,
Object.getOwnPropertyDescriptors({
foo: 123,
})
);
Object.getOwnPropertyDescriptors() 也可以用來(lái)實(shí)現(xiàn) Mixin(混入)模式。
let mix = (object) => ({
with: (...mixins) => mixins.reduce(
(c, mixin) => Object.create(
c, Object.getOwnPropertyDescriptors(mixin)
), object)
});
// multiple mixins example
let a = {a: 'a'};
let b = {b: 'b'};
let c = {c: 'c'};
let d = mix(c).with(a, b);
d.c // "c"
d.b // "b"
d.a // "a"
上面代碼返回一個(gè)新的對(duì)象 d ,代表了對(duì)象 a 和 b 被混入了對(duì)象 c 的操作。
出于完整性的考慮, Object.getOwnPropertyDescriptors() 進(jìn)入標(biāo)準(zhǔn)以后,以后還會(huì)新增 Reflect.getOwnPropertyDescriptors() 方法。
JavaScript
語(yǔ)言的對(duì)象繼承是通過(guò)原型鏈
實(shí)現(xiàn)的。ES6 提供了更多原型對(duì)象的操作方法。
__proto__
屬性(前后各兩個(gè)下劃線),用來(lái)讀取或設(shè)置當(dāng)前對(duì)象的原型對(duì)象
(prototype)。目前,所有瀏覽器(包括 IE11)都部署了這個(gè)屬性。
// es5 的寫法
const obj = {
method: function() { ... }
};
obj.__proto__ = someOtherObj;
// es6 的寫法
var obj = Object.create(someOtherObj);
obj.method = function() { ... };
該屬性沒(méi)有寫入 ES6 的正文,而是寫入了附錄,原因是 proto 前后的雙下劃線,說(shuō)明它本質(zhì)上是一個(gè)內(nèi)部屬性
,而不是一個(gè)正式的對(duì)外的 API,只是由于瀏覽器廣泛支持,才被加入了 ES6。標(biāo)準(zhǔn)明確規(guī)定,只有瀏覽器必須部署這個(gè)屬性,其他運(yùn)行環(huán)境不一定需要部署,而且新的代碼最好認(rèn)為這個(gè)屬性是不存在的。因此,無(wú)論從語(yǔ)義的角度,還是從兼容性的角度,都不要使用這個(gè)屬性,而是使用下面的 Object.setPrototypeOf()
(寫操作)、 Object.getPrototypeOf()
(讀操作)、 Object.create()
(生成操作)代替。
實(shí)現(xiàn)上, __proto__
調(diào)用的是Object.prototype.__proto__
,具體實(shí)現(xiàn)如下。
Object.defineProperty(Object.prototype, '__proto__', {
get() {
let _thisObj = Object(this);
return Object.getPrototypeOf(_thisObj);
},
set(proto) {
if (this === undefined || this === null) {
throw new TypeError();
}
if (!isObject(this)) {
return undefined;
}
if (!isObject(proto)) {
return undefined;
}
let status = Reflect.setPrototypeOf(this, proto);
if (!status) {
throw new TypeError();
}
},
});
function isObject(value) {
return Object(value) === value;
}
如果一個(gè)對(duì)象本身部署了 proto 屬性,該屬性的值就是對(duì)象的原型。
Object.getPrototypeOf({ __proto__: null })
// null
Object.setPrototypeOf
方法的作用與 __proto__
相同,用來(lái)設(shè)置一個(gè)對(duì)象的原型對(duì)象
(prototype),返回參數(shù)對(duì)象本身。它是 ES6 正式推薦的設(shè)置原型對(duì)象的方法。
// 格式
Object.setPrototypeOf(object, prototype)
// 用法
const o = Object.setPrototypeOf({}, null);
該方法等同于下面的函數(shù)。
function setPrototypeOf(obj, proto) {
obj.__proto__ = proto;
return obj;
}
下面是一個(gè)例子。
let proto = {};
let obj = { x: 10 };
Object.setPrototypeOf(obj, proto);
proto.y = 20;
proto.z = 40;
obj.x // 10
obj.y // 20
obj.z // 40
上面代碼將proto
對(duì)象設(shè)為 obj
對(duì)象的原型,所以從 obj 對(duì)象可以讀取 proto 對(duì)象的屬性。
如果第一個(gè)參數(shù)不是對(duì)象,會(huì)自動(dòng)轉(zhuǎn)為對(duì)象。但是由于返回的還是第一個(gè)參數(shù),所以這個(gè)操作不會(huì)產(chǎn)生任何效果。
Object.setPrototypeOf(1, {}) === 1 // true
Object.setPrototypeOf('foo', {}) === 'foo' // true
Object.setPrototypeOf(true, {}) === true // true
由于 undefined 和 null 無(wú)法轉(zhuǎn)為對(duì)象,所以如果第一個(gè)參數(shù)是 undefined 或 null ,就會(huì)報(bào)錯(cuò)。
Object.setPrototypeOf(undefined, {})
// TypeError: Object.setPrototypeOf called on null or undefined
Object.setPrototypeOf(null, {})
// TypeError: Object.setPrototypeOf called on null or undefined
該方法與Object.setPrototypeOf
方法配套,用于讀取一個(gè)對(duì)象的原型對(duì)象
。
Object.getPrototypeOf(obj);
下面是一個(gè)例子。
function Rectangle() {
// ...
}
const rec = new Rectangle();
Object.getPrototypeOf(rec) === Rectangle.prototype
// true
Object.setPrototypeOf(rec, Object.prototype);
Object.getPrototypeOf(rec) === Rectangle.prototype
// false
如果參數(shù)不是對(duì)象,會(huì)被自動(dòng)轉(zhuǎn)為對(duì)象。
// 等同于 Object.getPrototypeOf(Number(1))
Object.getPrototypeOf(1)
// Number {[[PrimitiveValue]]: 0}
// 等同于 Object.getPrototypeOf(String('foo'))
Object.getPrototypeOf('foo')
// String {length: 0, [[PrimitiveValue]]: ""}
// 等同于 Object.getPrototypeOf(Boolean(true))
Object.getPrototypeOf(true)
// Boolean {[[PrimitiveValue]]: false}
Object.getPrototypeOf(1) === Number.prototype // true
Object.getPrototypeOf('foo') === String.prototype // true
Object.getPrototypeOf(true) === Boolean.prototype // true
如果參數(shù)是 undefined 或 null ,它們無(wú)法轉(zhuǎn)為對(duì)象,所以會(huì)報(bào)錯(cuò)。
Object.getPrototypeOf(null)
// TypeError: Cannot convert undefined or null to object
Object.getPrototypeOf(undefined)
// TypeError: Cannot convert undefined or null to object
ES5 引入了 Object.keys
方法,返回一個(gè)數(shù)組
,成員是參數(shù)對(duì)象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵名。
var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)
// ["foo", "baz"]
ES2017 引入了跟 Object.keys
配套的Object.values
和 Object.entries
,作為遍歷一個(gè)對(duì)象的補(bǔ)充手段,供 for...of 循環(huán)使用。
let {keys, values, entries} = Object;
let obj = { a: 1, b: 2, c: 3 };
for (let key of keys(obj)) {
console.log(key); // 'a', 'b', 'c'
}
for (let value of values(obj)) {
console.log(value); // 1, 2, 3
}
for (let [key, value] of entries(obj)) {
console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}
Object.values
方法返回一個(gè)數(shù)組
,成員是參數(shù)對(duì)象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值。
const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]
返回?cái)?shù)組的成員順序,與本章的《屬性的遍歷》部分介紹的排列規(guī)則一致。
const obj = { 100: 'a', 2: 'b', 7: 'c' };
Object.values(obj)
// ["b", "c", "a"]
上面代碼中,屬性名
為數(shù)值
的屬性,是按照數(shù)值大小,從小到大遍歷的,因此返回的順序是 b 、 c 、 a 。
Object.values 只返回對(duì)象自身的可遍歷屬性。
const obj = Object.create({}, {p: {value: 42}});
Object.values(obj) // []
上面代碼中, Object.create 方法的第二個(gè)參數(shù)添加的對(duì)象屬性(屬性 p ),如果不顯式聲明,默認(rèn)是不可遍歷的,因?yàn)?p 的屬性描述對(duì)象的 enumerable 默認(rèn)是 false , Object.values 不會(huì)返回這個(gè)屬性。只要把 enumerable 改成 true , Object.values 就會(huì)返回屬性 p 的值。
const obj = Object.create({}, {p:
{
value: 42,
enumerable: true
}
});
Object.values(obj) // [42]
Object.values 會(huì)過(guò)濾屬性名為 Symbol 值的屬性。
Object.values({ [Symbol()]: 123, foo: 'abc' });
// ['abc']
如果 Object.values 方法的參數(shù)是一個(gè)字符串,會(huì)返回各個(gè)字符組成的一個(gè)數(shù)組。
Object.values('foo')
// ['f', 'o', 'o']
上面代碼中,字符串會(huì)先轉(zhuǎn)成一個(gè)類似數(shù)組的對(duì)象。字符串的每個(gè)字符,就是該對(duì)象的一個(gè)屬性。因此, Object.values 返回每個(gè)屬性的鍵值,就是各個(gè)字符組成的一個(gè)數(shù)組。
如果參數(shù)不是對(duì)象, Object.values 會(huì)先將其轉(zhuǎn)為對(duì)象。由于數(shù)值和布爾值的包裝對(duì)象,都不會(huì)為實(shí)例添加非繼承的屬性。所以, Object.values 會(huì)返回空數(shù)組。
Object.values(42) // []
Object.values(true) // []
Object.entries()
方法返回一個(gè)數(shù)組,成員是參數(shù)對(duì)象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值對(duì)數(shù)組。
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]
除了返回值不一樣,該方法的行為與 Object.values 基本一致。
如果原對(duì)象的屬性名是一個(gè) Symbol 值,該屬性會(huì)被忽略。
Object.entries({ [Symbol()]: 123, foo: 'abc' });
// [ [ 'foo', 'abc' ] ]
上面代碼中,原對(duì)象有兩個(gè)屬性,Object.entries
只輸出屬性名非 Symbol 值的屬性。將來(lái)可能會(huì)有Reflect.ownEntries()
方法,返回對(duì)象自身的所有屬性。
Object.entries
的基本用途是遍歷對(duì)象的屬性。
let obj = { one: 1, two: 2 };
for (let [k, v] of Object.entries(obj)) {
console.log(
`${JSON.stringify(k)}: ${JSON.stringify(v)}`
);
}
// "one": 1
// "two": 2
Object.entries
方法的另一個(gè)用處是,將對(duì)象
轉(zhuǎn)為真正的 Map 結(jié)構(gòu)
。
const obj = { foo: 'bar', baz: 42 };
const map = new Map(Object.entries(obj));
map // Map { foo: "bar", baz: 42 }
自己實(shí)現(xiàn) Object.entries 方法,非常簡(jiǎn)單。
// Generator函數(shù)的版本
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
// 非Generator函數(shù)的版本
function entries(obj) {
let arr = [];
for (let key of Object.keys(obj)) {
arr.push([key, obj[key]]);
}
return arr;
}
Object.fromEntries()
方法是Object.entries()
的逆操作,用于將一個(gè)鍵值對(duì)數(shù)組轉(zhuǎn)為對(duì)象。
Object.fromEntries([
['foo', 'bar'],
['baz', 42]
])
// { foo: "bar", baz: 42 }
該方法的主要目的,是將鍵值對(duì)
的數(shù)據(jù)結(jié)構(gòu)還原為對(duì)象
,因此特別適合將 Map 結(jié)構(gòu)轉(zhuǎn)為對(duì)象。
// 例一
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 }
該方法的一個(gè)用處是配合URLSearchParams
對(duì)象,將查詢字符串
轉(zhuǎn)為對(duì)象
。
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// { foo: "bar", baz: "qux" }
更多建議: