繁体   English   中英

LocalStorage 不更新然后存储新值

[英]LocalStorage not updating and then storing new values

我的目标是构建一个包含文本和数字的大型数据数组,文本是从预选的名称数组(名字和姓氏)中随机选择的。 函数 start() 是通过一个按钮激活的。

var malenames = ["John", "Bob", "Jim","Tim","Skylar","Zach","Jacob"];
var maleLast = ["J.","M.","B.","D.","W."];
var males = new Array();
males[0] = new Array("Placeholder","Placeholder",18);
males[1] = new Array("Placeholder","Placeholder",18);
males[2] = new Array("Placeholder","Placeholder",18);
males[3] = new Array("Placeholder","Placeholder",18);
males[4] = new Array("Placeholder","Placeholder",18);
males[5] = new Array("Placeholder","Placeholder",18);
males[6] = new Array("Placeholder","Placeholder",18);
males[7] = new Array("Placeholder","Placeholder",18);
males[8] = new Array("Placeholder","Placeholder",18);
males[9] = new Array("Placeholder","Placeholder",18);




function start() {
localStorage.setItem("random", Math.floor((Math.random()*(100-0))));
span.textContent = localStorage.getItem("random");


var i;
var j;
for (i=0; i < males.length; i++) {
males[i][0] = malenames[Math.floor(Math.random()*malenames.length)];
localStorage.setItem("males", JSON.stringify(males));
}

for (j=0; j<males.length; j++) {
males[j][1] = maleLast[Math.floor(Math.random()*maleLast.length)];
localStorage.setItem("males", JSON.stringify(males));
}



firstN.textContent = males[0][0];
lastN.textContent = males[0][1];
age.textContent = males[0][2];

}

此代码成功随机化,然后将名字和姓氏保存到 localStorage 中的数组中。 但是,我想通过每隔几秒向其添加一个值来修改计时器上的数字 18。

setInterval(function(){

var k;

for(k=0;k<males.length;k++){

males[k][2]++;
localStorage.setItem("males",JSON.stringify(males));


}
age.innerHTML = males[0][2];

}, 3000);

一切正常,所有内容都存储到 localStorage 中,直到我刷新页面。 当我刷新页面时,localStorage 数组仍然正确,直到发生间隔。 发生这种情况时,数组会刷新回 [Placeholder, Placeholder, 18]。 我很好奇为什么当我只尝试在每个时间间隔添加年龄变量时代码会这样做。 我很乐意接受反馈和解释来理解这一点。 谢谢你。

也许你真的想做一些更像的事情:

 function shuffle(a){ a.sort(function(b, c){ return 0.5 - Math.random(); }); } function RandomPeople(lastNameArray, firstNameArray){ var t = this; this.lastNames; this.firstNames; this.make = function(){ this.lastNames = lastNameArray.slice(); this.firstNames = firstNameArray.slice(); this.people = []; shuffle(this.firstNames); this.firstNames.forEach(function(n){ t.people.push([t.lastNames[Math.floor(Math.random()*t.lastNames.length)], n, 18]); }); return this; } this.grab = function(){ if(localStorage.people){ return JSON.parse(localStorage.people); } return false; } this.save = function(){ localStorage.people = JSON.stringify(this.people); return this; } } var men = new RandomPeople(['J.', 'M.', 'B.', 'D.', 'W.'], ['John', 'Bob', 'Jim', 'Tim', 'Skylar', 'Zach', 'Jacob']); var peps = men.grab(); if(!peps){ men.make(); peps[5][2] += 2; men.save(); peps = men.people; } console.log(peps);

暂无
暂无

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

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