有没有在JavaScript中定义json键的规则?

时间:2018-08-24 13:56:36

标签: javascript arrays object key

我正在学习JavaScript,并且正在寻找有关此信息的一段时间,但对此没有任何答案。我的问题是,是否有任何规则在JavaScript中定义JSON键。

例如,在python中有一个定义dict的规则,它是All the keys must be of an immutable data type such as strings, numbers, or tuples.

var json = {};
json[""] = "White space";
json[" "] = "Two white space";


var emptyJSON = {};
var emptyArray = [];
function a (){}
 
json[a] = "Function";
json[emptyJSON] = "Json";
json[emptyArray]= "Array";
//I don't know why this property whit an empty array does not appear when I console the json

console.log("Print the entire object =>", json);

//But it appears when I console the specific property  
console.log("Print empty array property =>", json[emptyArray]);

1 个答案:

答案 0 :(得分:2)

对象键是字符串。不是字符串的任何内容都将转换为字符串。

 var obj = {};

 obj[1] = 1;
 console.log(obj["1"]);

 obj[{}] = 2;
 console.log(obj["[Object object]"]);

 obj[[1, 2]] = 3;
 console.log(obj["1,2"]);