简体   繁体   English

如何将变量作为键传递给javascript unshift / push?

[英]how do I pass a variable as key into a javascript unshift/push?

I'm trying to set a variable name in an unshift() call like so: 我试图像这样在unshift()调用中设置变量名称:

var new_index_name = priv.indices[i]["name"], // e.g. "container"
    new_index_array.unshift({new_index_name :[]});

But my new_index_array will now contain: 但是我的new_index_array现在将包含:

[ {new_index_name : []} ]

instead of 代替

[ {"container" : []} ]

Question: 题:
Is it possible to pass a variable name as the key value in a push/unshift call? 是否可以在推送/取消移位调用中将变量名作为key传递?

Thanks for help! 感谢帮助!

This has nothing to do with push or unshift 这与pushunshift无关

You can't use a variable as a property in an object literal (since you can use identifiers for property names, and variables are also represented by identifiers). 您不能将变量用作对象文字中的属性(因为可以将标识符用作属性名,并且变量也由标识符表示)。

You have to construct the object, then add the data to it. 您必须构造对象,然后将数据添加到其中。

var new_index_name = priv.indices[i]["name"], // e.g. "container"
var ob = {};
    ob[new_index_name] = [];
    new_index_array.unshift(ob);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM