English 中文(简体)
Localstorage & JSON.parse: 如果没有价值,联合材料就停止工作?
原标题:Localstorage & JSON.parse: If no value, JS stops working?
最佳回答

为此:

alert(JSON.parse(localStorage[ test ] || null));

之所以失败,是因为JSON.parse(未界定_variable) 造成“无效性质”错误。 如果存在<条码>,就会产生错误。 以上代码为<代码>null,如果该数值为 falsy,即un specified。 但是,如果数值为<>0、>><>>>>>或另一 falsy数值,则该数值确实有不利影响。 如果需要更具体的法典,则尝试:

alert(JSON.parse(typeof localStorage[ test ] == "undefined" ? null : localStorage[ test ]));
问题回答

在当地使用 储存,您需要在其编码中预测数据可能不存在,并且需要测试这一状况,并以某种方式处理。 这样做的最简单办法是:

var rawData = localStorage.getItem("something");
var parsedData = {};  // set whatever the default value should be if there is no localStorage value
if (rawData) {
    parsedData = JSON.parse(rawData);
}

也可以使用例外处理方法:

var parsedData;
try {
    parsedData = JSON.parse(localStorage.getItem("something"));
} catch(e) {
    parsedData = {};    // set default value if localStorage parsing failed
}

此外,你应学会如何看到你在青.或白白.的错误中的 j字错误。 Javascript wasn t “block. 它留下了一个错误,未经处理,因此无法执行。 这一错误(线数和错误类型)在错误的焦耳中和你所看到的虚线上都存在。





相关问题
passing form variables into a url with php

I have the following form which allows a user to select dates/rooms for a hotel reservation. <form action="booking-form.php" method="post"> <fieldset> <div class="select-date">...

Error: "Cannot modify the return value" c#

I m using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable? public Point Origin { get; set; } Origin.X = 10; // fails with CS1612 Error ...

C-style Variable initialization in PHP

Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?

C#/.NET app doesn t recognize Environment Var Change (PATH)

In my C# app, I am programmatically installing an Oracle client if one is not present, which requires adding a dir to the PATH system environment variable. This all works fine, but it doesn t take ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

How to dynamically generate variables in Action Script 2.0

I have a for loop in action script which I m trying to use to dynamically create variable. Example for( i = 0 ; i &lt 3 ; i++) { var MyVar+i = i; } after this for loop runs, i would like to ...

热门标签