今天在学习localStorage时,写了一个例子,结果在Chrome中显示了这样一个错误:SyntaxError: Illegal return statement
具体代码如下
if (!window.localStorage) {
alert("浏览器不支持localStorage属性");
return false;
}
else{
//localStorage写入方法,三种
var storage = window.localStorage;
storage["a"] = 1;
storage.b = 2;
storage.setItem("c",3);
console.log(typeof storage["a"]);
console.log(typeof storage["b"]);
console.log(typeof storage["c"]);
}
通过查找报错原因https://blog.csdn.net/qq_16339527/article/details/52004269
发现是return语句位置不当发生了错误
应该给if else语句块套上一个函数,return语句才能正常执行
window.onload = function(){
//使用localStorage属性时,先判断浏览器是否支持该属性
if (!window.localStorage) {
alert("浏览器不支持localStorage属性");
return false;
}
else{
//localStorage写入方法,三种
var storage = window.localStorage;
storage["a"] = 1;
storage.b = 2;
storage.setItem("c",3);
console.log(typeof storage["a"]);
console.log(typeof storage["b"]);
console.log(typeof storage["c"]);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/ba71ae5d236f586b9b8f547540a665d5.png)