JS中數組與對象的遍歷方法實例

1、數組的遍歷: css

首先定義一個數組html

arr=['snow','bran','king','nightking'];
複製代碼

一、for循環,須要知道數組的長度; 二、foreach,沒有返回值,能夠不知道數組長度;vue

arr.forEach(function(ele,index){
console.log(index);
console.log(ele)
})
複製代碼

三、map函數,遍歷數組每一個元素,並回調操做,須要返回值,返回值組成新數組,原數組不變;node

var newarr=arr.map(function(i){
  return "hello "+i
});//歡迎加入全棧開發交流圈一塊兒學習交流:864305860
console.log(newarr)
複製代碼

四、filter函數:過濾經過條件的元素組成一個新數組,原數組不變;webpack

var newarr=arr.filter(function(i){
  return i == "bran"
});
console.log(newarr)
複製代碼

五、some函數,遍歷數組中是否有符合條件的函數,返回布爾值;web

var yy=arr.some(function(i){
  return i.length>4
});
console.log(yy)       //true
複製代碼

六、every函數,遍歷數組是否每一個元素都符合條件,返回布爾值;面試

var xx=arr.every(function(i){
  return i.length>4
});//歡迎加入全棧開發交流圈一塊兒學習交流:864305860
console.log(xx)       //false
複製代碼

七、reduce函數,爲數組中的每個元素依次執行回調函數 語法:數組

arr.reduce(callback, initialValue)
[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
 return previousValue + currentValue;
});//歡迎加入全棧開發交流圈一塊兒學習交流:864305860
複製代碼

callback:執行數組中每一個值的函數,包括四個參數; previousValue:上一次調用回調返回的值,或者是提供的初始值(initialValue); currentValue:當前被處理的值; index:當前元素在數組中的索引; array:調用reduce的數組; initialValue:做爲第一次調用callback的第一個參數; 例如:bash

var total = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
});
// total == 6
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
複製代碼

要提供initialValue的話:函數

var total = [0, 1, 2, 3].reduce(function(a, b) {
   return a + b;
},4);//歡迎加入全棧開發交流圈一塊兒學習交流:864305860
console.log(total); //10
複製代碼

2、對象的遍歷

var obj={snow:1,bran:2,king:3,nightking:4};
for(let i in obj){
  console.log(i+','+obj[i])
}
複製代碼

in也能夠用來遍歷數組,不過i對應於數組的key值:

for(let i in arr){
  console.log(i+','+arr[i])
}//歡迎加入全棧開發交流圈一塊兒學習交流:864305860
複製代碼

結語

感謝您的觀看,若有不足之處,歡迎批評指正。 本次給你們推薦一個免費的學習羣,裏面歸納移動應用網站開發,css,html,webpack,vue node angular以及面試資源等。 對web開發技術感興趣的同窗,歡迎加入Q羣:864305860,無論你是小白仍是大牛我都歡迎,還有大牛整理的一套高效率學習路線和教程與您免費分享,同時天天更新視頻資料。 最後,祝你們早日學有所成,拿到滿意offer,快速升職加薪,走上人生巔峯。

相關文章
相關標籤/搜索