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