forEach() 和 $.each() ,$().each

forEach(): value在前,index在後 主體:數組
$.each() index在前,value在後 主體:數組
$().each index在前,value在後 主體:單個婚配元素

JS forEach()

語法: array.forEach(function(currentValue, index, arr), thisValue)


html

<p>點擊按鈕將數組中的一切值乘以特定数字。</p>
<p>乘以: <input type="number" id="multi" value="10"></p>
<button onclick="numbers.forEach(myFunction)">點我</button>
<p>盤算后的值: <span id="demo"></span></p>
 
 
<script>
var numbers = [65, 44, 12, 4];      
function myFunction(item,index,arr) {  // 當前元素,當前元素索引,當前元素地點數組
    arr[index] = item * document.getElementById("multi").value;
    demo.innerHTML = numbers;
}
</script>

《forEach() 和 $.each() ,$().each》

Jq: $.each()

語法: $.each(arr,function(index,item))


    var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
    function myfunc(index,item){
          alert(item[0])
         }
    $.each(arr2,myfunc);    //輸出:1   4   7



Jq:$().each

語法:$(selector).each(function(index,element))

  
 $(document).ready(function(){
      $("button").click(function(){
        $("li").each(func);   //each() 要領為每一個婚配元素規定要運轉的函數
      })
    });

function func(index,el){
      console.log(index+$(this).text());
    }
    
html:
    
<button>輸出每一個列表項的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>    
        
    原文作者:orangecat00
    原文地址: https://segmentfault.com/a/1190000014959256
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞