我想要做的是将输入表单中的一些数据存储到一个数组中,但是如果它不存在则有任何方法可以创建数组然后运行脚本的其余部分,否则,如果确实存在则继续也有相同的脚本。
我想将数组存储为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
}
答案 0 :(得分:1)
路由变量是否已声明?
如果是这样,你应该能够做到这样的事情:
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']);
});
答案 1 :(得分:0)
只需将代码放在if语句后面:
if(routes) {
// do nothing
} else {
var routes = [];
}
// do the code for both cases
或者,没有“没有”:
if( ! routes) {
var routes = [];
}
// do the code