jQuery localStorage and arrays



我正在尝试做的是将输入表单中的一些数据存储到数组中,但是如果数组不存在,则有没有办法创建数组,然后运行脚本的其余部分,否则,如果它确实存在,那么也继续使用相同的脚本。

我想将数组存储为 localStorage,以便稍后我可以显示这些项目。

var routes = [];
div.on('click', function() {
   routes.push({ routeF : $('input[name=routeFrom]').val() });
   routes.push({ routeT : $('input[name=routeTo]').val() });
   routes.push({ leaving : $('select').val() });
   localStorage['routes'] = JSON.stringify(routes);
   var storedRoutes = JSON.parse(localStorage['routes']);
});

我希望能够在不做的情况下做到这一点:

if(routes[]) {
    //do code
} else { 
    var routes = []; 
    //do same code
}

路由变量是否已声明?

如果是这样,您应该能够执行以下操作:

div.on('click', function() {
  // The following line will set routes to an empty array if set.
  // Be careful here, as if you have not declared routes as a variable,
  // it will become a global variable.
  (!routes || !routes.length) && (routes = []);
  // End Change ...
  routes.push({ routeF : $('input[name=routeFrom]').val() });
  routes.push({ routeT : $('input[name=routeTo]').val() });
  routes.push({ leaving : $('select').val() });
  localStorage['routes'] = JSON.stringify(routes);
  var storedRoutes = JSON.parse(localStorage['routes']);
});

只需将代码放在 if 语句后面:

if(routes) {
    // do nothing
} else { 
    var routes = []; 
}
// do the code for both cases

或者,没有"什么都没有":

if( ! routes) {
    var routes = []; 
}
// do the code

最新更新