常用的JavaScript數組方法
1、filter()
語法:
array.filter(function(currentValue,index,arr), thisValue)
參數說明:
currentValue
:當前元素對象(必選)
index
:當前元素的索引值(可選)
arr
:當前元素屬于的數組對象(可選)
thisValue
:對象作為該執(zhí)行回調時使用,傳遞給函數,用作 "this" 的值。
如果省略了 thisValue
,"this
" 的值為 "undefined
"(可選)
//過濾年齡大于10的元素 var ages = [5, 32, 7, 10, 33, 12, 40]; var res = ages.filter(function (currentValue) { return currentValue > 10; }) console.log(res.toString()); //輸出結果:32,33,12,40 //箭頭函數寫法 var res1 = ages.filter(item => item > 10) console.log(res.toString());
輸出結果:
32,33,12,40
2、forEach()
語法:
array.forEach(function(currentValue, index, arr), thisValue)
參數用法同上
//循環(huán)輸出每個參數 var ages = [5, 32, 7, 10, 33, 12, 40]; ages.forEach(function (currentValue, index) { console.log("參數:" + currentValue + "索引:" + index); }) //箭頭函數寫法 ages.forEach((item, index) => { console.log("參數:" + item + "索引:" + index); })
再看下面一段代碼:
//把10修改成20 var ages = [5, 32, 7, 10, 33, 12, 40]; ages.forEach(function (currentValue, index) { if (currentValue === 10) { ages[index] = 20 return } console.log(index); }) console.log(ages);
我們在代碼中將10的值改成20后,加了一個return
,但是運行結果顯示還是打印了7次index的值,這就是forEach的一個缺點,只有循環(huán)結束才能停止。那如何解決呢?
3、some()
語法:
array.some(function(currentValue,index,arr),thisValue)
參數用法同上
//把10修改成20 var ages = [5, 32, 7, 10, 33, 12, 40]; ages.some(function (currentValue, index) { if (currentValue === 10) { ages[index] = 20 return true } console.log(index); }) console.log(ages); //把10修改成20 箭頭函數 var ages = [5, 32, 7, 10, 33, 12, 40]; ages.some((item, index) => { if (item === 10) { ages[index] = 20 return true } console.log(index); }) console.log(ages);
上面的代碼中運行結果只會打印三次index
的值,通過some
就可以完美解決forEach()
的不足,開發(fā)過程中就看大家的需要就行選擇。
4、every()
語法:
array.every(function(currentValue,index,arr), thisValue)
參數用法同上
//判斷每個元素的值是否都大于4 var ages = [5, 32, 7, 10, 33, 12, 40]; var res = ages.some(function (currentValue) { return currentValue > 4 }) console.log(res); //輸出:true //箭頭函數 var res = ages.some(item => item > 4) console.log(res);
5、reduce()
語法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
參數說明:
total
:必需。初始值, 或者計算結束后的返回值。
currentValue
: 必需。當前元素
currentIndex
:可選。當前元素的索引
arr
:可選。當前元素所屬的數組對象。
initialValue
:可選。傳遞給函數的初始值
//計算所有元素的和 var numbers = [15.5, 2.3, 1.1, 4.7]; var res = numbers.reduce(function (total, currentValue) { return total += currentValue }, 0) console.log(res); //23.6 //計算大于4的元素的和 var result = numbers.filter(item => item > 4).reduce((total, item) => total += item, 0) console.log(result); //20.2
6、合并數組
用法:var arr = [...數組1,...數組2]
結果:將數組2的元素值拼接到數組1元素值后面
var arr = [1, 2, 3] var arr2 = [4, 5, 6] var res = [...arr, ...arr2] console.log(res); //輸出結果:[1, 2, 3, 4, 5, 6] var res = [...arr2, ...arr] console.log(res); //輸出結果: [4, 5, 6, 1, 2, 3]
到此這篇關于常用的JavaScript數組方法的文章就介紹到這了,更多相關 數組 JavaScript內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript生成器函數Generator?Functions優(yōu)缺點特性詳解
這篇文章主要為大家介紹了JavaScript生成器函數Generator?Functions的特性及優(yōu)點詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05