數組迭代方法簡介:

forEach:

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

  • 參數:

    • function:必須,接收三個參數,currentValue(當前元素,必須),index(當前元素索引值,可選),arr(當前元素所屬數組,可選)。
    • thisValue:可選,
  • 返回值:undefined。

  • 例:

	var sum =0;
	var numbers = [1,2,3,4,5];
	numbers.forEash(function(item){
		sum+=item;
	});
	console.log(sum)  //15

map:

  • 語法:
	array.map(function(currentValue,index,arr),thisValue)
  • 參數:

    • function:必須,接收三個參數。currentValue(當前元素值,必須),index(當前元素索引值,可選),arr(當前元素所屬數組,可選)
    • thisValue:可選,
  • 返回值:新數組,數組中的元素爲原始數組元素調用函數處理後的值。

  • 例:

	var numbers = [1,2,3,4,5];
	var sum = numbers.map(function(item){
		item+1;
	});
	console.log(sum)  //[2,3,4,5,6]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章