這篇文章主要介紹了javascript如何遍歷方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
有用到object對象的轉換成數組,然后又想到了遍歷方法,所以,也想記錄下
1. 終止或者跳出循環
break跳出循環體,所在循環體已結束
continue跳出本次循環,進行下一次循環,所在的循環體未結束
return 終止函數執行
for (let i = 0; i < 5; i++) { if (i == 3) break; console.log("The number is " + i); /* 只輸出 0 , 1 , 2 , 到3就跳出循環了 */ } for (let i = 0; i <= 5; i++) { if (i == 3) continue; console.log("The number is " + i); /* 不輸出3,因為continue跳過了,直接進入下一次循環 */ }
2.遍歷方法
假數據
const temporaryArray = [6,2,3,4,5,1,1,2,3,4,5]; const objectArray = [ { id: 1, name: 'd' }, { id: 2, name: 'd' }, { id: 3, name: 'c' }, { id: 1, name: 'a' } ]; const temporaryObject = { a: 1, b: 2, c: 3, d: 4, }; const length = temporaryArray.length;
普通for循環遍歷
for(let i = 0; i < length; i++) { console.log(temporaryArray[i]); }
for in 循環
/* for in 循環主要用于遍歷普通對象, * 當用它來遍歷數組時候,也能達到同樣的效果, * 但是這是有風險的,因為 i 輸出為字符串形式,而不是數組需要的數字下標, * 這意味著在某些情況下,會發生字符串運算,導致數據錯誤 * */ for(let i in temporaryObject) { /* hasOwnProperty只加載自身屬性 */ if(temporaryObject.hasOwnProperty(i)) { console.log(temporaryObject[i]); } }
for of 循環,用于遍歷可迭代的對象
for(let i of temporaryArray) { console.log(i); }
forEach 第一個值為數組當前索引的值,第二個為索引值,只能遍歷數組,無返回值,也無法跳出循環
let a = temporaryArray.forEach(function(item, index) { console.log(index, item); });
map 返回新數組,只能遍歷數組
temporaryArray.map(function(item) { console.log(item); });
filter 是數組的內置對象,不改變原數組,有返回值
temporaryArray.filter(function(item) { console.log(item%2 == 0); });
some判斷是否有符合的值
let newArray = temporaryArray.some(function(item) { return item > 1; }); console.log(newArray);
every判斷數組里的值是否全部符合條件
let newArray1 = temporaryArray.every(function(item) { return item > 6; }); console.log(newArray1);
reduce(function(total, currentValue, currentIndex, array) {}, [])
total:初始值或者計算結束后的返回值, currentValue遍歷時的當前元素值,currentIndex當前索引值,array當前數組
如果沒有指定參數-空數組[],累積變量total默認是第一個元素的值
在指定參數空數組后,累積變量total的初始值就變成了空數組
let temporaryObject3 = {}; let newArray2 = objectArray.reduce(function(countArray, currentValue) { /* 利用temporaryObject3里存放id來判斷原數組里的對象是否相同,若id相同,則繼續下一步,不同則將該對象放入新數組中 * 則countArray為去重后的數組 * */ temporaryObject3[currentValue.id] ? '' : temporaryObject3[currentValue.id] = true && countArray.push(currentValue); return countArray; }, []); console.log(newArray2);
感謝你能夠認真閱讀完這篇文章,希望小編分享javascript如何遍歷方法內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。