Object.getOwnPropertySymbols() 方法返回一个给定对象自身的所有 Symbol 属性的数组。

语法

Object.getOwnPropertySymbols(obj)

参数

obj
要返回 Symbol 属性的对象。

返回值

在给定对象自身上找到的所有 Symbol 属性的数组。

描述

Object.getOwnPropertyNames()类似,您可以将给定对象的所有符号属性作为 Symbol 数组获取。 请注意,Object.getOwnPropertyNames()本身不包含对象的 Symbol 属性,只包含字符串属性。

因为所有的对象在初始化的时候不会包含任何的 Symbol,除非你在对象上赋值了 Symbol 否则Object.getOwnPropertySymbols()只会返回一个空的数组。

示例

var obj = {};
var a = Symbol("a");
var b = Symbol.for("b");

obj[a] = "localSymbol";
obj[b] = "globalSymbol";

var objectSymbols = Object.getOwnPropertySymbols(obj);

console.log(objectSymbols.length); // 2
console.log(objectSymbols)         // [Symbol(a), Symbol(b)]
console.log(objectSymbols[0])      // Symbol(a)

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Object.getOwnPropertySymbols
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
Object.getOwnPropertySymbols
Draft  

浏览器兼容

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
getOwnPropertySymbolsChrome Full support 38Edge Full support 12Firefox Full support 36IE No support NoOpera Full support 25Safari Full support 9WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support YesFirefox Android Full support 36Opera Android Full support 25Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12

Legend

Full support  
Full support
No support  
No support

相关链接