js中in運算子,forEach與map的用法-基礎知識總結------彭記(016)

來源:互聯網
上載者:User

標籤:基礎知識   關注   prot   size   obj   for   key   each   tostring   

in運算子:

<script>    /*1.能夠遍曆對象的屬性*/    var obj = {        ‘name‘:‘jack‘,        age:20    };    for(var key in obj){        console.log(key + ":" + obj[key]);    }    /*2.還可以判斷 對象 是否可以訪問某個屬性,而不關注這個屬性是否在當前對象中定義*/    console.log(‘name‘ in obj); //true    console.log(‘toString‘ in obj); // true    console.log(‘toString1‘ in obj); // false</script>

forEach的使用:

 

<script>    /*forEach用來遍曆數組*/    //var arr= [123,2,4,35,435,65,7,658,67,98];    /*    value:當前遍曆到元素值    index:當前元素的索引    arr:當前遍曆的數組    * */    /*arr.forEach(function(value,index,arr){        console.log(value + ":" + index + ":" + arr);    })*/    /*自訂forEach函數*/    Array.prototype.myForEach = function(callback){        for(var i =0;i<arr.length;i++){            callback(this[i],i,this);        }    }    var arr1= [123,2,4,35,435,65,7,658,67,98];    arr1.myForEach(function(value,index){        console.log(value + ":" + index + ":" + arr1);    });</script>

 

map的使用:

 

<script>    var arr= [123,2,4,35,435,65,7,658,67,98];    /*將數組值翻倍,再儲存到數組*/    /*1.使用for*/    //var newArr=[];    /*for (var i = 0; i < arr.length; i++) {        var obj = arr[i];        newArr.push(obj*2);    }    console.log(newArr);*/    /*2.使用forEach*/    /*arr.forEach(function(value,index,arr){        newArr.push(value*2);    });    console.log(newArr);*/    /*3.使用map函數*/    /*arr.map(function(value,index,arr){        newArr.push(value*2);    });    console.log(newArr);*/    /*map會將結果儲存到一個新產生的數組中再返回*/   /* var newArr = arr.map(function(value,index,arr){        return value * 2;    });    console.log(newArr);*/    /*map的實現原理*/    Array.prototype.myMap = function(callback){        var temp = [];        for(var i=0;i<this.length;i++){            var v = callback(this[i],i,this);            if(v){                temp.push(v);            }        }        return temp;    };    var newArr = arr.myMap(function(value,index,arr){        return value * 2;    });    console.log(newArr);</script>

 

js中in運算子,forEach與map的用法-基礎知識總結------彭記(016)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.