I want to make an array that will have a few usernames in it and the array will be in the localstorage but if you have already have the username include the array so its wont add it again. Tried very much !!
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>
Here would be my approach:
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)
}
In my opinion you need to pass the current user to save to the function.
In the else part of your code, use the following snippet:
var flag=0;
for each (var item in username)
{
if(user.value == item)
{
flag=1;
}
}
if(!flag)
{
username.push(user.value);
localStorage.setItem('username', username);
}
You can only store string in the localStorage
. So, you've to convert array to string and string back to array when getting data from localStorage
.
See the comments inline in the code:
var username;
function save(user) {
// To get the data from localStorage
var localUsernames = localStorage.getItem('username') || '';
username = localUsernames.split(',');
// Get the username array from localStorage if available, or create an empty array
if (username.indexOf(user.value) === -1) {
username.push(user.value);
}
// Convert the array into string and then store in the localStorage
localStorage.setItem('username', username.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.