javascript中基本数据类型有七种:Number、Bigint、String、undefined、null、Boolean、Symbol
Symbol,这个东西是2016年ES6标准里添加的
看看例子:
let k1 = Symbol();
let k2 = Symbol();
let k3 = Symbol(1);
let k4 = Symbol(1.0);
let k5 = Symbol("1");
let k6 = Symbol("kkk");
let k7 = 12;
let k8 = "12";
let kvs = {
[k1]: "v1-k1",
[k2]: "v2-k2",
[k3]: "v3-k3",
[k4]: "v4-k4",
[k5]: "v5-k5",
[k6]: "v6-k6",
[k7]: "v7-k7",
[k8]: "v8-k8"
};
for (let k in kvs) {
console.log("k = ", k, ", v = ", kvs[k]); //k = 12 , v = v8-k8,#其它用symbol做键的都隐藏无法访问(不可枚举)
}
console.log("js = ", JSON.stringify(kvs)); //js = {"12":"v8-k8"} #symbol都是不可枚举的
console.log("k1 == k2,", k1 == k2, ", k1 = ", k1, ", k2 = ", k2); //k1 == k2, false , k1 = Symbol() , k2 = Symbol() #每个Symbol值都是唯一的
let arr = [k1, k2, k3, k4, k5, k6];
for (let i in arr) {
console.log("a i = ", i, ", v = ", arr[i], ", kvs=", kvs[arr[i]]); //symbol是不可枚举,需要直接使用kvs[symbol]才能取到值
}
let syms = Object.getOwnPropertySymbols(kvs); //只获得所有的symbol属性
for (let i in syms) {
console.log("getSymbols i = ", i, ", symbolKey = ", syms[i], ", v = ", kvs[syms[i]]);
// console.log("getSymbols k = ", k, ", v = ", kvs[k]);
}
console.log("typefof k1 = ", typeof(k1), ", k1 = ", k1, "typeof k1=", typeo