欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS基本遍歷方法詳解

 更新時間:2023年09月08日 08:31:52   作者:編程三昧  
這篇文章主要給大家介紹了JS基本遍歷方法,for,for...in,for...of,文章通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下

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, 6

for...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
// c

for...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 關(guān)鍵字來終止循環(huán),也可以使用 continue 關(guān)鍵字來跳過本次循環(huán)。
  • for...of 循環(huán)的適用范圍最大。

以上就是JS基本遍歷方法的詳細內(nèi)容,更多關(guān)于JS遍歷方法的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論