简体   繁体   English

如何将变量用作对象中的键?

[英]How can I use a variable as a key in an object?

Is this possible? 这可能吗? The real world example is here: 现实世界的例子在这里:

var userKey = "userIdKey";

chrome.storage.sync.set({ userKey: "Hello World" }, function () {
    chrome.storage.sync.get(userKey, function (data) {
        console.log("In sync:", data);
    });

    console.log("Success");
});

This example currently fails because the getter looks for "userIdKey" where as the setter interprets the variable literally as "userKey" 此示例当前失败,因为getter查找“userIdKey”,其中setter将变量字面解释为“userKey”

UPDATE: I am fully aware of accessing a variable via array notation. 更新:我完全了解通过数组表示法访问变量。 The realworld example I have provided is for the creation of the object. 我提供的真实世界示例是用于创建对象。 I am hoping to ensure that the same key is always used for getting and setting -- rather than relying on two string constants being kept in sync. 我希望确保始终使用相同的密钥来获取和设置 - 而不是依赖于两个字符串常量保持同步。

var myObject = {},
    objectKey = 'Foo',
    myObject[objectKey] = 'Baz';

console.log(myObject[objectKey]);

The proper way is : 正确的方法是:

    var key = "something";
    Object.defineProperty(d, key, {
        get: function() {return this.getFullYear() },
        set: function(y) { this.setFullYear(y) }
    });

Or in your case: 或者在你的情况下:

chrome.storage.sync.defineProperty(this, userKey, {
    get: function() {return this[userKey];},
    set: function(value) {this[userKey] = value};
});

Read HERE for more on this. 请阅读此处了解更多相关信息。 Object.prototype.defineProperty is new and not available in legacy mode, but the polyfill is available as Object.prototype.__defineGetter__ and Object.prototype.__defineSetter__ . Object.prototype.defineProperty是新的,在遗留模式下不可用,但Object.prototype.__defineGetter__可用作Object.prototype.__defineGetter__Object.prototype.__defineSetter__

Access it like an array: 像数组一样访问它:

myObject['Foo']

To set: 设置:

myObject['Foo'] = "Bar"

Or as a variable: 或者作为变量:

var key = "Foo";
myObject[key] = "Bar"

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

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