js系列-for循環for in,for of,forEach循環遍歷

1.for循環:使用最平凡,但注意使用let定義變量,原因上篇文章已說明 

for (let index = 0; index < array.length; index++) { }

2.for...in遍歷:用於遍歷對象的可枚舉屬性(包括它的原型鏈上的可枚舉屬性),for/in主要用於遍歷對象(最常用於調試),不建議用來遍歷數組。

原因:因爲迭代的順序是依賴於執行環境的,所以數組遍歷不一定按次序訪問元素。因此當迭代訪問順序很重要的數組時,最好用整數索引去進行for循環(或者使用 Array.prototype.forEach() 或 for...of 循環)。

//遍歷對象
   let obj = {
        name: 'zhang',
        age: 28
    };
    Object.getPrototypeOf(obj).sex = '男'
    for (const key in obj) {
        console.log(key);//打印: name age sex
    }
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {//對象的hanOwnProperty屬性我們會在原型中講解
            console.log(key);//打印: name age
        }
    }
//遍歷數組
    let arr = ['item1', 'item2', 'item3'];
    for (let key in arr) {
        console.log(key);
    }

3.for of遍歷:用來遍歷 Arrays(數組), Strings(字符串), Maps(映射), Sets(集合), NodeList(DOM節點集合)等可迭代的數據結構。

    //迭代Array
    let arr = [10, 20, 30];
    for (let value of arr) {
        value += 1;
        console.log(value);
    }// 11 21 31
    //如果你不想修改語句塊中的變量 , 也可以使用const代替let。
    let arrs = [10, 20, 30];
    for (const value of arrs) {
        console.log(value);
    }//10 20 30

    //迭代String
    let strs = "boo";
    for (let value of strs) {
        console.log(value);
    }//  "b"  "o"  "o"

    //迭代Map
    let map = new Map([["a", 1], ["b", 2], ["c", 3]]);
    for (let entry of map) {
        console.log(entry);
    }// ["a", 1] ["b", 2] ["c", 3]

    for (let [key, value] of map) {
        console.log(value);
    }// 1 2 3

    //迭代 Set
    let set = new Set([1, 2, 3]);
    for (const value of set) {
        console.log(value);
    }

    //遍歷DOM元素
    <body>
        <ul>
            <li></li>
            <li></li>
        </ul>
    </body>
    let lis = document.querySelectorAll("li");
    for (const li of lis) {
        li.addEventListener("click", function () {
            this.style.backgroundColor = "red";
        });
    }

4.forEach

forEach使函數作用在每個數組元素上,但是沒有返回值。

下面例子是截取標籤的五個字符。

let lessons = [
	{title: '媒體查詢響應式佈局',category: 'css'},
  {title: 'FLEX 彈性盒模型',category: 'css'},
	{title: 'MYSQL多表查詢隨意操作',category: 'mysql'}
];

lessons.forEach((item, index, array) => {
    item.title = item.title.substr(0, 5);
});
console.log(lessons);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章