【问题标题】:Push varaibles into an array with containing variables - Javascript将变量推送到包含变量的数组中 - Javascript
【发布时间】:2021-11-29 02:32:53
【问题描述】:

我有密码

var myArray = []

myArray.push( { "bob" : { "banana" : "yellow" } })

console.log(myArray)

返回

{
    "bob": {
        "banana": "yellow"
    }
}

现在,我想像这样更改变量:

var myArray = []

var name = "bob"
var fruit = "banana"
var fruitcolor = "yellow"

myArray.push( { name : { fruit : fruitcolor } })

console.log(myArray)

但它不会返回相同的结果。我该如何解决这个问题?

谢谢!

【问题讨论】:

  • myArray.push( { [name] : { [fruit] : fruitcolor } })。使用括号表示法。

标签: javascript arrays variables push


【解决方案1】:

如果要将字符串设置为对象的键,则必须使用bracket notation

替换

myArray.push( { name : { fruit : fruitcolor } })

与:

myArray.push( { [name] : { [fruit] : fruitcolor } })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多