简体   繁体   English

本地存储不接受来自对象的值

[英]local storage not accepting value from object

im trying to set x's age to the local storage item 'age' however, for a reason i do not know, this will not work.我试图将 x 的年龄设置为本地存储项目“年龄”,但是,由于我不知道的原因,这将不起作用。

Here is my code:这是我的代码:

var x = {
age: 37,
gender: "male",
income: 17000,
};
localStorage.setItem("age") = x.age;
alert(localStorage.getItem('age'));

The problem is with your syntax .问题在于您的语法 You need to use it this way.你需要这样使用它。

localStorage.setItem("age", x.age)

alert(localStorage.getItem('age'));

The idea is simple.这个想法很简单。 You are storing the data against a name.您正在根据名称存储数据。 And then retrieve it using the same name.然后使用相同的名称检索它。

Open the Developer Tools in your browser.在浏览器中打开开发者工具。 Look at the console.看控制台。

Uncaught TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present.未捕获的类型错误:无法在“存储”上执行“setItem”:需要 2 个参数,但仅存在 1 个。

Then look at the manual which says:然后看看手册上说:

 storage.setItem(keyName, keyValue);

Then get your syntax correct:然后让你的语法正确:

var x = {
  age: 37,
  gender: "male",
  income: 17000,
};
localStorage.setItem("age", x.age);
alert(localStorage.getItem('age'));

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

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