我通过两种不同的方式创建对象,并尝试访问它们并操纵它们。我通过对象构造函数创建的对象可以工作,但我尝试通过文字符号做的同样的事情不起作用。我不明白。
这是代码,它会比我更好地解释自己:
var numberOne = new Object();
rand = Math.random();
numberOne[rand] = "random number";
console.log(numberOne); //return 0.6761925128922479: "random number"
var numberTwo = {}; //code doesnt work.
numberTwo.rando = Math.random();
numberTwo[rando] = "another random number";
console.log(numberTwo); //error
最佳答案
它不起作用,因为您的索引随机保存到 numberTwo 对象中而不是 rando 变量中。您需要引用保存到 numberTwo 对象中的索引,如下所示:
numberTwo[numberTwo.rando];
所以,你的代码必须是这样的:
var numberTwo = {};
numberTwo.rando = Math.random(); // numberTwo.rando contains some random number
numberTwo[numberTwo.rando] = "another random number"; //now it is correct
关于javascript - 在 javascript 中创建对象并操作属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303855/