将变量推入包含变量的数组 - Javascript
Push varaibles into an array with containing variables - Javascript
我有密码
var myArray = []
myArray.push( { "bob" : { "banana" : "yellow" } })
console.log(myArray)
哪个return
{
"bob": {
"banana": "yellow"
}
}
现在,我想像这样更改变量:
var myArray = []
var name = "bob"
var fruit = "banana"
var fruitcolor = "yellow"
myArray.push( { name : { fruit : fruitcolor } })
console.log(myArray)
但 return 结果不同。我该如何解决这个问题?
谢谢!
如果要将字符串设置为对象的键,则必须使用 bracket notation
替换
myArray.push( { name : { fruit : fruitcolor } })
与 :
myArray.push( { [name] : { [fruit] : fruitcolor } })
我有密码
var myArray = []
myArray.push( { "bob" : { "banana" : "yellow" } })
console.log(myArray)
哪个return
{
"bob": {
"banana": "yellow"
}
}
现在,我想像这样更改变量:
var myArray = []
var name = "bob"
var fruit = "banana"
var fruitcolor = "yellow"
myArray.push( { name : { fruit : fruitcolor } })
console.log(myArray)
但 return 结果不同。我该如何解决这个问题?
谢谢!
如果要将字符串设置为对象的键,则必须使用 bracket notation
替换
myArray.push( { name : { fruit : fruitcolor } })
与 :
myArray.push( { [name] : { [fruit] : fruitcolor } })