$.each()和$().each(),以及forEach()的用法

1.forEach是js中遍歷數組的方法,以下javascript

var arr=[1,2,3,4];
arr.forEach(function(val,index,arr){//val爲數組中當前的值,index爲當前值的下表,arr爲原數組
    arr[index]=2*val;
});
console.log(arr);//結果是修改了原數組,爲每一個數乘以2

 

2.$.each()是jquery中遍歷數組的方法,以下html

var arr=[1,2,3,4];
$.each(arr,function(i,n){
    alert("索引"+i+"對應的值"+n);
});

 

3.$().each()方法規定爲每一個匹配元素規定運行的函數,以下:java

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                $("li").each(function(){
                    alert($(this).text())
                });
            });
        });
    </script>
</head>
<body>
<button>輸出每一個列表項的值</button>
<ul>
    <li>Coffee</li>
    <li>Milk</li>
    <li>Soda</li>
</ul>
</body>
</html>
相關文章
相關標籤/搜索