我有这样的代码。
var key = "anything"; var object = { key: "key attribute" };
我想知道是否有一种方法可以用“任何东西”代替 key。
key
喜欢
var object = { "anything": "key attribute" };
是的,你可以用:
var key = "anything"; var json = { }; json[key] = "key attribute";
或者,如果在编写程序时手边有值,那么只需使用第二个方法即可。
没有直接的方法。
但这个应该可以:
json[key] = json.key; json.key = undefined;
有点棘手,但是,嘿,它工作!
这应该会奏效:
var key = "anything"; var json = {}; json[key] = "key attribute";
在 ES6中,使用 一个 href = “ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object _ initializer # Computed _ property _ Names”rel = “ norefrer”> Computed property name 。
const key = "anything"; const object = { [key]: "key attribute" // ^^^^^ COMPUTED PROPERTY NAME };
注意 key周围的方括号。你实际上可以在方括号中指定任何表达式,而不仅仅是一个变量。
闭包非常适合这种情况。
function keyValue(key){ return function(value){ var object = {}; object[key] = value; return object; } } var key = keyValue(key); key(value);
解决方案:
最近需要一个解决方案,如何设置 Cookie 传递动态 json 键值。 使用 https://github.com/js-cookie/js-cookie#json,它可以很容易地完成。 希望将用户选择的每个选项值存储在 Cookie 中,这样在选项卡或浏览器关闭时不会丢失。
var json = { option_values : {} }; $('option:selected').each(function(index, el) { var option = $(this); var optionText = option.text(); var key = 'option_' + index; json.option_values[key] = optionText; Cookies.set('option_values', json, { expires: 7 } ); });
然后可以使用 检索每个页面加载上的每个 cookie 键值
Cookies.getJSON('option_values');
在现代 Javascript (ECMAScript 6)中,你可以用方括号将变量排序:
var key = "anything"; var json = { [key]: "key attribute" };