JS基本遍歷方法詳解
for
這大概是應用最廣的循環(huán)語句了吧,簡單實用,且大多數(shù)時候性能還是在線的,唯一的缺點大概就是太普通,沒有特色,導致很多人現(xiàn)在不愿用它。
const array = [4, 7, 9, 2, 6];
for (const index = 0; index < array.length; index++) {
const element = array[index];
console.log(element);
}
// 4, 7, 9, 2, 6for...in
for...in 語句可以以任意順序遍歷一個對象的除 Symbol 以外的可枚舉屬性。
const temp = {name: "temp"};
function Apple() {
this.color = 'red';
}
Apple.prototype = temp;
const obj = new Apple();
for (const prop in obj) {
console.log(`obj.${ prop } = ${ obj[prop] }`);
}
// obj.color = red
// obj.name = temp如果你只要考慮對象本身的屬性,而不是它的原型,那么使用 getOwnPropertyNames() 或執(zhí)行 hasOwnProperty() 來確定某屬性是否是對象本身的屬性。
const temp = {name: "temp"};
function Apple() {
this.color = 'red';
}
Apple.prototype = temp;
const obj = new Apple();
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(`obj.${ prop } = ${ obj[prop] }`);
}
}
// obj.color = red當然,也可以用來遍歷數(shù)組。
const arr = [1, 2, 3, 4, 5];
for (const key in arr) {
console.log(key)
}
// 0,1,2,3,4使用 for...in 可以遍歷數(shù)組,但是會存在以下問題:
index 索引為字符串型數(shù)字(注意,非數(shù)字),不能直接進行幾何運算。
遍歷順序有可能不是按照實際數(shù)組的內(nèi)部順序(可能按照隨機順序)。
所以一般不建議使用 for...in 來遍歷數(shù)組。
for...of
for...of 語句在可迭代對象(包括 Array,Map,Set,String,TypedArray,arguments 對象等等)上創(chuàng)建一個迭代循環(huán),調(diào)用自定義迭代鉤子,并為每個不同屬性的值執(zhí)行語句。
const array = ['a', 'b', 'c'];
for (const element of array) {
console.log(element);
}
// a
// b
// cfor...of 和 for...in 的區(qū)別:
for...in語句以任意順序迭代對象的可枚舉屬性。for...of語句遍歷可迭代對象定義要迭代的數(shù)據(jù)。
Object.prototype.objCustom = function () { };
Array.prototype.arrCustom = function () { };
let iterable = [3, 5, 7];
iterable.foo = 'hello';
for (const key in iterable) {
console.log(key); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
// 0, 1, 2, "foo", "arrCustom", "objCustom"
for (const key of iterable) {
console.log(key);
}
// 3, 5, 7使用 for...of 遍歷 Map 結(jié)構(gòu):
let nodes = new Map();
nodes.set("node1", "t1")
.set("node2", "t2")
.set("node3", "t3");
for (const [node, content] of nodes) {
console.log(node, content);
}
// node1 t1
// node2 t2
// node3 t3可以看出,使用 for...of 遍歷 Map 結(jié)構(gòu)還是挺方便的,推薦使用!
總結(jié)
- 如果普通 for 循環(huán)用膩了,推薦使用
for...of來替代。 - 這三種循環(huán)都可以使用 break 關鍵字來終止循環(huán),也可以使用 continue 關鍵字來跳過本次循環(huán)。
for...of循環(huán)的適用范圍最大。
以上就是JS基本遍歷方法的詳細內(nèi)容,更多關于JS遍歷方法的資料請關注腳本之家其它相關文章!
相關文章
javascript 中設置window.location.href跳轉(zhuǎn)無效問題解決辦法
這篇文章主要介紹了javascript 中設置window.location.href跳轉(zhuǎn)無效問題解決辦法的相關資料,需要的朋友可以參考下2017-02-02
JavaScript裝飾器函數(shù)(Decorator)實例詳解
這篇文章主要介紹了JavaScript裝飾器函數(shù)(Decorator),結(jié)合實例形式分析了JavaScript裝飾器函數(shù)(Decorator)的功能、實現(xiàn)與使用方法,需要的朋友可以參考下2017-03-03
javascript 對象數(shù)組根據(jù)對象object key的值排序
本文僅僅是實現(xiàn)了javascript 對象數(shù)組根據(jù)對象object key的值排序,算是對自己學習javascript這么久的一個小結(jié),希望大家能夠喜歡2015-03-03
Bootstrap選項卡與Masonry插件的完美結(jié)合
這篇文章主要介紹了Bootstrap選項卡與Masonry插件的完美結(jié)合的相關資料,需要的朋友可以參考下2016-07-07
JS中數(shù)組與對象相互轉(zhuǎn)換的實現(xiàn)方式
這篇文章主要介紹了JS中數(shù)組與對象相互轉(zhuǎn)換的實現(xiàn)方式,文章通過代碼示例講解的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2024-04-04

