我正在尝试从localstorage中获取一系列名称中的随机名称选择器,这似乎是当我使用谷歌浏览器检查时错误不会弹出。
这是我的代码:
function getUserData() {
var Detail = localStorage.getItem("Detail");
if (Detail == null) {
Detail = []; // on new computer, create the local storage item } else {
Detail = JSON.parse(Detail); // convert from string to array
}
for (var i = 0; i < Detail.length; i++) { // loop through the array
var row = document.getElementById("Detail").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = Detail[i].name;
cell2.innerHTML = Detail[i].admin;
cell3.innerHTML = Detail[i].email;
cell4.innerHTML = Detail[i].contact;
cell5.innerHTML = Detail[i].country;
}
}
function NamePicker() {
var Detail = localStorage.getItem("Detail");
if (Detail == null) {
Detail = []; // on new computer, create the local storage item
} else {
Detail = JSON.parse(Detail); // convert from string to array
}
// copy names
var nameArray = [];
for (var i = 0; i < Detail.length; i++) { // loop through the array
nameArray[i] = Detail[i].name;
}
for (var i = 0; i < Detail.length; i++) { // loop through the array
// get a number from random num generator %numArray.length
name = nameArray[num];
while (nameArray.length < 11) {
var randomnumber = Math.max(Math.ceil(Math.random() * 11))
var found = false;
for (var i = 0; i < nameArray.length; i++) {
if (name[i] == randomnumber) {
found = true;
break
}
}
if (!found) name[nameArray.length] = randomnumber;
}
// Display using modal
alert(name);
// remove using splice(num, 1);
name.splice(num, 1);
document.getElementById("Detail").innerHTML = name;
}
}
问题是num
似乎没有从列表中删除名称,警报功能不会弹出......
我非常感谢提前帮助感谢...
答案 0 :(得分:1)
我在你的第二个功能中发现了一些问题;你在三个for循环中使用局部变量i,我认为在其中一个中你打算使用num。此外,我在第二个for循环中将Detail.length更改为nameArray.length,因为您要通过nameArray。我还将第三个for循环更改为使用z而不是i。
function NamePicker() {
var Detail = localStorage.getItem("Detail");
if (Detail == null) {
Detail = []; // on new computer, create the local storage item
} else {
Detail = JSON.parse(Detail); // convert from string to array
}
// copy names
var nameArray = [];
for (var i = 0; i < Detail.length; i++) { // loop through the array
nameArray[i] = Detail[i].name;
}
for (var num = 0; num < nameArray.length; num++) { // loop through the array
// get a number from random num generator %numArray.length
name = nameArray[num];
while (nameArray.length < 11) {
var randomnumber = Math.max(Math.ceil(Math.random() * 11))
var found = false;
for (var z = 0; z < nameArray.length; z++) {
if (name[z] == randomnumber) {
found = true;
break
}
}
if (!found) name[nameArray.length] = randomnumber;
}
// Display using modal
alert(name);
// remove using splice(num, 1);
name.splice(num, 1);
document.getElementById("Detail").innerHTML = name;
}
}
希望有所帮助!