4

I need to store an object in localStorage - and I know that in order to do so, I have to convert the object into a string. All cool.

My problem is in actually creating the object in the first place: I have two values in sessionStorage that need to be added to the object which is then passed into localStorage. However, when I try to create the object, one value is being stored as the variable name rather than its (numeric) value. Any idea whats going on here?

var siteName = sessionStorage['1'];
var siteID = (+sessionStorage['2']);
var temp = {siteID:siteName};
alert(typeof siteID);
alert(JSON.stringify(temp));

The first alert confirms that siteID is indeed a number type, but the second alert shows that the variable name (siteID) is stored rather than its numeric value.

4

2 に答える 2

4

この行:

var temp = {siteID:siteName};

siteId...変数から取得した値で呼び出されるプロパティを含むオブジェクトを作成しsiteNameます。

プロパティ名をsiteID変数から取得する場合は、次のようにします。

var temp = {};
temp[siteID] = siteName;

または、ES2015 (別名「ES6」) では、新しい計算されたプロパティ名の構文を使用できます。

// ES2015+ only!
var temp = {[siteId]: siteName};

JavaScript では、2 つの異なる方法でオブジェクトのプロパティにアクセス/作成することができます。

obj.foo = "bar";    // Creates a `foo` property on `obj` with the value `"bar"`

...または括弧付き表記と文字列を使用:

obj["foo"] = "bar"; // Does the same thing

あなたのようなオブジェクト初期化子のキーは、var temp = {siteID:siteName};常に文字どおりに使用されます (ただし、オプションで引用符で囲むこともできます)。オブジェクト初期化子では、代わりに変数からキーを取得する方法はありません。そのため、最初にオブジェクトを作成し、次にプロパティを設定する 2 段階のプロセスとして行う必要があります。

だから、あなたがするなら

temp[siteID] = siteName;

... の数値はsiteID文字列に変換されてプロパティ名になり、 の値が値siteNameになります。

var temp = {};
var key = 1;
temp[key] = "value";
console.log(temp[1]); // "value"
console.log(temp["1"]); // "value"

([今のところ] JavaScript では、プロパティ名は常に文字列です。)

于 2012-05-16T13:21:39.427 に答える
2

これに変更します。

var temp = {};

temp[siteName] = siteID;

または、typeofテストがプロパティ名を表示することを意図していた場合は、それらを逆にします。

var temp = {};

temp[siteID] = siteName;

ただし、それsiteID以降は文字列と見なされることに注意してください。

于 2012-05-16T13:21:30.837 に答える