用户名将保存在localStorage中的数组

时间:2015-08-05 05:47:14

标签: javascript

我想创建一个数组,其中包含一些用户名,数组将在localstorage中,但是如果你已经拥有了包含数组的用户名,那么它不会再添加它。 非常尝试!!

的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>

3 个答案:

答案 0 :(得分:1)

这是我的方法:

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)
}

在我看来,你需要传递当前用户保存到该功能。

答案 1 :(得分:0)

在代码的else部分中,使用以下代码段:

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);
}

答案 2 :(得分:0)

您只能在localStorage中存储字符串。因此,在从localStorage获取数据时,您必须将数组转换为字符串并将字符串转换回数组。

请参阅代码中的内联注释:

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());
}