Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่างระหว่าง for...in และ for...of ใน JavaScript

ความแตกต่างระหว่าง for...in และ for...of

ทั้งสอง loop วนลูปผ่านสิ่งต่างกัน ความแตกต่างหลักคือสิ่งที่พวกมันวนลูป

1) for...in loop

วนลูปผ่าน enumerable properties ของออบเจ็กต์ในลำดับ arbitrary สนใจแค่ properties ไม่สนใจ values

ตัวอย่าง: ใช้ for...in วน properties ของอาร์เรย์ เนื่องเป็นอาร์เรย์ Index เป็น property สำคัญ จึงวน index ทุกตัว รวม inherited properties เช่น "inherProp2", "inherProp1"

ตัวอย่างที่ 1

<html> <body> <script> 
    Object.prototype.inherProp1 = function() {}; 
    Array.prototype.inherProp2 = function() {}; 
    var org = ["Apple", "Microsoft", "Tesla"]; 
    org.anotherOrg = "solarCity"; 
    for (var key in org) { 
        document.write(key); 
        document.write("<br>"); 
    } 
</script> </body> </html>

ผลลัพธ์

0 1 2 anotherOrg // own property inherProp2 // inherited property inherProp1 // inherited property

ตัวอย่างที่ 2: ใช้ hasOwnProperty() แสดงเฉพาะ own properties (indexes และ properties เพิ่มเติม) ไม่แสดง inherited properties

ตัวอย่างที่ 2

<html> <body> <script> 
    Object.prototype.objCustom = function() {}; 
    Array.prototype.arrCustom = function() {}; 
    var org = ["Apple", "Microsoft", "Tesla"]; 
    org.anotherOrg = "solarCity"; 
    for (var i in org) { 
        if (org.hasOwnProperty(i)) { 
            document.write(i); 
            document.write("<br>"); 
        } 
    } 
</script> </body> </html>

ผลลัพธ์

0 1 2 anotherOrg

2) for...of loop

ต่างจาก for...in, for...of วนลูปผ่าน values ที่ออบเจ็กต์กำหนดให้วนได้

ตัวอย่าง: แสดง values 'Apple', 'Microsoft', 'Tesla' ด้วย for...of

ตัวอย่าง

<html> <body> <script> 
    var org = ["Apple", "Microsoft", "Tesla"]; 
    for (var key of org) { 
        document.write(key); 
        document.write("<br>"); 
    } 
</script> </body> </html>

ผลลัพธ์

Apple Microsoft Tesla