1. 程式人生 > >第十周web作業

第十周web作業

array foo www 遍歷 example scrip mozilla 構造 沒有

作業一、For each in,For in和For of(explain,examples)

一、一般的遍歷數組的方法:

    var array = [1,2,3,4,5,6,7];  
    for (var i = 0; i < array.length; i) {  
        console.log(i,array[i]);  
    }  

二、用for in的方遍歷數組

    for(let index in array) {  
        console.log(index,array[index]);  
    };  

三、forEach

技術分享圖片 技術分享圖片
array.forEach(v=>{  
    console.log(v);  
});
array.forEach(function(v){  
    console.log(v);  
});
 
技術分享圖片 技術分享圖片

四、用for in不僅可以對數組,也可以對enumerable對象操作

var A = {a:1,b:2,c:3,d:"hello world"};  
for(let k in A) {  
    console.log(k,A[k]);  
} 

五、在ES6中,增加了一個for of循環,使用起來很簡單

技術分享圖片 技術分享圖片
    for(let v of array) {  
        console.log(v);  
    };  

let s = "helloabc";

for(let c of s) {

console.log(c);

}

 
技術分享圖片 技術分享圖片

總結來說:for in總是得到對像的key或數組,字符串的下標,而for of和forEach一樣,是直接得到值
結果for of不能對象用
對於新出來的Map,Set上面

技術分享圖片 技術分享圖片
    var set = new Set();  
    set.add("a").add("b").add("d").add("c");  
    var map = new Map();  
    map.set("a",1).set("b",2).set(999,3);  
    for (let v of set) {  
        console.log(v);  
    }  
    console.log("--------------------");  
    for(let [k,v] of map) {  
        console.log(k,v);  
    }  
技術分享圖片 技術分享圖片

javascript遍歷對象詳細總結

1.原生javascript遍歷

(1)for循環遍歷

let array1 = [‘a‘,‘b‘,‘c‘];
for (let i = 0;i < array1.length;i++){
  console.log(array1[i]);  // a  b  c 
}

(2)JavaScript 提供了 foreach() map() 兩個可遍歷 Array對象 的方    

forEach和map用法類似,都可以遍歷到數組的每個元素,而且參數一致;

Array.forEach(function(value , index , array){ //value為遍歷的當前元素,index為當前索引,array為正在操作的數組
  //do something
},thisArg)      //thisArg為執行回調時的this值

不同點:

forEach() 方法對數組的每個元素執行一次提供的函數。總是返回undefined;

map() 方法創建一個新數組,其結果是該數組中的每個元素都調用一個提供的函數後返回的結果。返回值是一個新的數組;

例子如下:

技術分享圖片 技術分享圖片
var array1 = [1,2,3,4,5];
 
var x = array1.forEach(function(value,index){
 
    console.log(value);   //可遍歷到所有數組元素
 
    return value + 10
});
console.log(x);   //undefined    無論怎樣,總返回undefined
 
var y = array1.map(function(value,index){
 
    console.log(value);   //可遍歷到所有數組元素
 
    return value + 10
});
console.log(y);   //[11, 12, 13, 14, 15]   返回一個新的數組
技術分享圖片 技術分享圖片

對於類似數組的結構,可先轉換為數組,再進行遍歷

技術分享圖片 技術分享圖片
let divList = document.querySelectorAll(‘div‘);   //divList不是數組,而是nodeList
 
//進行轉換後再遍歷
[].slice.call(divList).forEach(function(element,index){
  element.classList.add(‘test‘)
})
 
 
Array.prototype.slice.call(divList).forEach(function(element,index){
  element.classList.remove(‘test‘)
})
 
[...divList].forEach(function(element,index){   //<strong>ES6寫法</strong>
  //do something
})
技術分享圖片 技術分享圖片

(3)for ··· in ··· / for ··· of ···

for...in 語句以任意順序遍歷一個對象的可枚舉屬性。對於每個不同的屬性,語句都會被執行。每次叠代時,分配的是屬性名  

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

技術分享圖片 技術分享圖片
let array2 = [‘a‘,‘b‘,‘c‘]
let obj1 = {
  name : ‘lei‘,
  age : ‘16‘
}
 
for(variable  in array2){   //variable  為 index
  console.log(variable )   //0 1 2
}
 
for(variable  in obj1){   //variable 為屬性名
  console.log(variable)   //name age
}
技術分享圖片 技術分享圖片

ES6新增了 遍歷器(Iterator)機制,為不同的數據結構提供統一的訪問機制。只要部署了Iterator的數據結構都可以使用 for ··· of ··· 完成遍歷操作 ( Iterator詳解 : http://es6.ruanyifeng.com/#docs/iterator ),每次叠代分配的是 屬性值

原生具備 Iterator 接口的數據結構如下:

Array Map Set String TypedArray 函數的arguments對象 NodeList對象

技術分享圖片 技術分享圖片
let array2 = [‘a‘,‘b‘,‘c‘]
let obj1 = {
  name : ‘lei‘,
  age : ‘16‘
}
 
for(variable  of array2){   //<strong>variable  為 value</strong>
  console.log(variable )   //‘a‘,‘b‘,‘c‘
}
 
for(variable  of obj1){  //<strong>普通對象不能這樣用</strong>
  console.log(variable)   // 報錯 : main.js:11Uncaught TypeError: obj1[Symbol.iterator] is not a function
}<br><br>let divList = document.querySelectorAll(‘div‘);<br><br>for(element of divlist){  //可遍歷所有的div節點<br>  //do something <br>}
技術分享圖片 技術分享圖片

如何讓普通對象可以用for of 進行遍歷呢? http://es6.ruanyifeng.com/#docs/iterator 一書中有詳細說明了!

  除了叠代時分配的一個是屬性名、一個是屬性值外,for in 和 for of 還有其他不同 (MDN文檔: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of)

    for...in循環會遍歷一個object所有的可枚舉屬性。

    for...of會遍歷具有iterator接口的數據結構

    for...in 遍歷(當前對象及其原型上的)每一個屬性名稱,而 for...of遍歷(當前對象上的)每一個屬性值

技術分享圖片 技術分享圖片
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
 
let iterable = [3, 5, 7];
iterable.foo = "hello";
 
for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
 
for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}
技術分享圖片 第一個作業借鑒於:https://www.cnblogs.com/amujoe/p/8875053.html 作業二、constructor vs object source constructor的定義和用法:constructor 屬性返回對創建此對象的數組函數的引用。 語法:object.constructor 舉例說明constructor屬性: 技術分享圖片技術分享圖片 作業三、Arrow function restore 箭頭函數表達式的語法比函數表達式短,並且不綁定自己的 this,arguments,super或 new.target。此外,箭頭函數最好在非方法函數中使用,且不能用作構造函數。 語法: 1.基礎語法: (param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression // 等價於: => { return expression; } // 如果只有一個參數,圓括號是可選的: (singleParam) => { statements } singleParam => { statements } // 無參數或者多參數的箭頭函數需要使用圓括號或者下劃線: () => { statements } _ => { statements } 2.高級語法: // 只返回一個對象字面量,沒有其他語句時, 應當用圓括號將其包起來: params => ({foo: bar}) // 支持 Rest parameters 和 default parameters: (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } // 支持參數列表中的解構賦值 var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6 箭頭函數的引入有兩個方面的作用:一是更簡短的函數書寫,二是對 this的詞法解析。 1.更短的函數: var a = [ "Hydrogen", "Helium", "Lithium", "Beryl-lium" ]; var a2 = a.map(function(s){ return s.length }); var a3 = a.map( s => s.length ); 2.不綁定this: function Person() { // 構造函數 Person() 定義的 `this` 就是新實例對象自己 this.age = 0; setInterval(function growUp() { // 在非嚴格模式下,growUp() 函數定義了其內部的 `this`為全局對象, 不同於構造函數Person()的定義的 `this` this.age++; } , 1000); } var p = new Person(); // 在 ECMAScript 3/5 中,這個問題通過把this的值賦給變量, // 然後將該變量放到閉包中來解決。 function Person() { var self = this; // 也有人選擇使用 `that` 而非 `self`. // 只要保證一致就好. self.age = 0; setInterval(function growUp() { // 回調裏面的 `self` 變量就指向了期望的那個對象了 self.age++; } , 1000); }
箭頭函數會捕獲其所在上下文的 this 值,作為自己的 this 值,因此下面的代碼將如期運行。function Person() this.age = 0
  setInterval(() => {
    this.age++; // this正確地指向了person對象
  }, 1000);
}

var p = new Person();

作業三借鑒於:https://www.jianshu.com/p/bb0da0356013

作業四、Event Flow mechanism(事件流)
概念:HTML中與javascript交互是通過事件驅動來實現的,例如鼠標點擊事件、頁面的滾動事件onscroll等等,
可以向文檔或者文檔中的元素添加事件偵聽器來預訂事件。
要知道這些事件是在什麽時候進行調用的,就需要了解一下“事件流”的概念。

什麽是事件流:

  1,DOM事件流,

  "DOM2事件流"規定的事件流包括三個階段:

    1,事件捕獲階段。

    2,處於目標階段。

    3,事件冒泡階段。

js中一種綁定事件的方式:

技術分享圖片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件流</title>
    <script>

    window.onload = function(){

        var oBtn = document.getElementById(‘btn‘);

        oBtn.addEventListener(‘click‘,function(){
            console.log(‘btn處於事件捕獲階段‘);
        }, true);
        oBtn.addEventListener(‘click‘,function(){
            console.log(‘btn處於事件冒泡階段‘);
        }, false);

        document.addEventListener(‘click‘,function(){
            console.log(‘document處於事件捕獲階段‘);
        }, true);
        document.addEventListener(‘click‘,function(){
            console.log(‘document處於事件冒泡階段‘);
        }, false);

        document.documentElement.addEventListener(‘click‘,function(){
            console.log(‘html處於事件捕獲階段‘);
        }, true);
        document.documentElement.addEventListener(‘click‘,function(){
            console.log(‘html處於事件冒泡階段‘);
        }, false);

        document.body.addEventListener(‘click‘,function(){
            console.log(‘body處於事件捕獲階段‘);
        }, true);
        document.body.addEventListener(‘click‘,function(){
            console.log(‘body處於事件冒泡階段‘);
        }, false);

    };

    </script>
</head>
<body>
    <a href="javascript:;" id="btn">按鈕</a>
</body>
</html>

運行效果:

技術分享圖片



1,addEventListener


  addEventListener是DOM2級事件新增的指定事件處理程序的操作,這個方法接收3個參數:要處理的事件名,作為事件處理程序的函數和一個布爾值,最後這個布爾值如果是true,表示在捕獲階段調用事件處理程序;如果是false,表示在冒泡階段調用事件處理程序。


  2,document,documentElement和document.body三者之間的關系:


    document代表的是整個html頁面,


    document.documentElement代表是的<html>標簽。


    document.body代表的是<body>標簽。

出現上圖結果的原因是:

  在標準的“DOM2級事件”中規定,事件流首先是經過事件捕獲階段,接著是處於目標階段,最後是事件冒泡階段。這裏可以畫個圖示意一下:

技術分享圖片

首先在事件捕獲過程中,document對象首先接收到click事件,然後事件沿著DOM樹依次向下,一直傳播到事件的實際目標。就是id為btn的標簽。

  接著在事件冒泡的過程中,時間開始是由具體的元素(a標簽)接收,然後逐級向上傳播到較為不具體的節點。

jQuery的常用事件:

技術分享圖片



 


摘自https://www.cnblogs.com/lbjiu/

第十周web作業