我想创建一个数组,其中包含一些用户名,并且该数组将位于本地存储中,但如果您已经有用户名,则包含该数组,因此它不会再次添加它。 非常努力!!
JavaScript
var username;
function save() {
username = ["ssfs", "s", "v"];
for (var i = 0; i <= 8; i++)
if (username.indexOf(user.value) >= 0) {
break;
} else {
username.push(user.value);
localStorage.setItem('username', username)
}
i++
}
body {
margin: 0 auto;
width: 100%;
height: 100vh;
display: inline-block;
text-align: center;
}
input {} button {
width: 10%;
display: inline-block;
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div id='main' class="main">
<header></header>
<input type="text" id="user" placeholder="Name" />
<br>
<input type="password" placeholder="password" />
<br>
<input type="password" placeholder="password Confirm" />
<br>
<br>
<button onclick="save()">Save</button>
<button>Home Page</button>
<footer></footer>
<div>
</body>
最佳答案
这是我的方法:
var username;
username = ["ssfs","s","v"];
function save(user){
var isAlreadyInserted = false;
//loop through your username array to check
for (var i = 0; i < username.length; i++) {
if (username[i] === currentUserName) {
isAlreadyInserted = true;
}
}
//if the username is not in the array, insert it
if (!isAlreadyInserted) {
username.push(user.value);
}
localStorage.setItem('username', username)
}
在我看来,您需要传递当前用户才能保存到该函数。
关于javascript - 将保存在 localStorage 中的用户名数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31824296/