宗策

导航

JavaScript-数组案例

 

案例一:

遍历数组

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function myfn(){
        var i1 = document.getElementById("i1");
        var i2 = document.getElementById("i2");
        var ul = document.getElementById("myul");
        var arr = i1.value.split(i2.value);
        //得到数组后90%的可能性是遍历
        for(var i=0;i<arr.length;i++){
            ul.innerHTML+="<li>"+arr[i]+"</li>";
        }
    }
</script>
</head>
<body>
<input type="text" id="i1">
<input type="text" id="i2">
<input type="button" value="添加" onclick="myfn()"> 
<hr>
<ul id="myul"></ul>
</body>
</html>
View Code

效果:

 

 

 案例二:

数组自定义排序:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var arr = [3,10,5,18,16,28];
    //自定义排序方法
    function mysort(a,b){
        //return a-b; 升序
        return b-a;  //降序
    }
    alert(arr.sort(mysort));
/*     var persons = [p1,p2,p3,p4];
    function mysort(a,b){
        return a.salary-b.salary; 升序
    } */
    
    

</script>
</head>
<body>

</body>
</html>
View Code

 

案例三:

密码校验

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    .ok{
        color: green;
    }
    .err{
        color: red;
    }
</style>
<script type="text/javascript">
function checkUsername(){
    var i1 = document.getElementById("i1");
    var s1 = document.getElementById("s1");
    var reg = /^\w{8,16}$/;
    s1.className = reg.test(i1.value)?"ok":"err";
}
function checkPassword(){
    var i2 = document.getElementById("i2");
    var s2 = document.getElementById("s2");
    var reg = /^\w{8,16}$/;
    s2.className = reg.test(i2.value)?"ok":"err";
}
</script>
</head>
<body>
<input type="text" id="i1" placeholder="请输入用户名"
    onblur="checkUsername()">
<span id="s1">8-16位数字字母下划线组成</span>
<input type="password" id="i2" onblur="checkPassword()"
 placeholder="请输入密码">
<span id="s2">8-16位数字字母下划线组成</span> 
</body>
</html>
View Code

 

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><style type="text/css">.ok{color: green;}.err{color: red;}</style><script type="text/javascript">function myfn(){var i1 = document.getElementById("i1");var i2 = document.getElementById("i2");var s1 = document.getElementById("s1");var s2 = document.getElementById("s2");var reg = /^\w{8,16}$/;s1.className = reg.test(i1.value)?"ok":"err";s2.className = reg.test(i2.value)?"ok":"err";}</script></head><body><input type="text" id="i1" placeholder="请输入用户名"><span id="s1">8-16位数字字母下划线组成</span><input type="password" id="i2" placeholder="请输入密码"><span id="s2">8-16位数字字母下划线组成</span> <input type="button" value="校验" onclick="myfn()"> </body></html>




posted on 2020-05-07 17:49  宗策  阅读(171)  评论(0编辑  收藏  举报