有没有办法在JavaScript对象文字中使用变量键? [英] Is there a way to use variable keys in a JavaScript object literal?

查看:79
本文介绍了有没有办法在JavaScript对象文字中使用变量键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码。

var key = "anything";   
var object = {   
    key: "key attribute"  
};

我想知道是否有办法替换密钥带任何。

I want to know if there is a way to replace that key with "anything".

喜欢

var object = {  
    "anything": "key attribute"     
};


推荐答案

是的。您可以使用:

var key = "anything";
var json = { };
json[key] = "key attribute";

如果您在编写程序时拥有值,则只需使用第二种方法。

Or simply use your second method if you have the values at hand when writing the program.

这篇关于有没有办法在JavaScript对象文字中使用变量键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆