JS中模拟用户注册登录利用localStorage存储多个值

<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input type="text" id="username"><br>
	<input type="passowrd" id="password"><br>
	<button id="login">登录</button>
	<button id="regist">注册</button>
</body>
<script>
	//对象
	// var obj = {username:"a",password:"123",score:1000}
	// console.log(obj.username);
	//先获取所有用户的对象//变成数组
	if(window.localStorage.userArr){//判断是否存在
		var array = JSON.parse(window.localStorage.userArr);
	}else{
		array = [];//创建一个新数组
	}
	//登录
	document.getElementById('login').onclick = function(){
		var username = document.getElementById('username').value;
		var password = document.getElementById('password').value;
		var isHad = false;//定义一个开关变量
		var index = 0 ; //定义一个下标确定用户
		//遍历数组进行匹配
		for(var i =0;i<array.length;i++){
			if(username==array[i].username){//有这个账号
				isHad=true;
				index=i;

			}
		}
		if(isHad){//如果存在
			if(password==array[index].password){
				alert("登录成功");
			}else{
				alert("密码错误");
			}
		}else{//账号不存在或输入错误
			alert('账号不存在或输入错误');
		}
	}

	//注册
	document.getElementById('regist').onclick = function(){
		var username = document.getElementById('username').value;
		var password = document.getElementById('password').value;
		//遍历数组进行匹配
		for(var i =0;i<array.length;i++){
			//判断是否有相同账号
			if(username==array[i].username){
				alert("该账号已存在");
				return;
			}
		}
		//创建对象
		var obj = {username:username,password:password,score:0}
		array.push(obj);
		window.localStorage.userArr=JSON.stringify(array);
		alert("用户创建成功");

	}

</script>
</html>

猜你喜欢

转载自blog.csdn.net/lanseguhui/article/details/81287444