- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- JavaScript中三種for循環(huán)語(yǔ)句的使用總結(for、for
每個(gè)接觸JS的開(kāi)發(fā)人員都不可避免的與for循環(huán)打交道,畢竟這是遍歷必不可少的工具之一。JavaScript 中的 for 循環(huán)語(yǔ)句相信大家都已經(jīng)快用厭了,現在有好多文章都在講怎么減少代碼中的 for 循環(huán)語(yǔ)句,但是,你又不得不承認它們真的很有用。今天,我來(lái)總結一下前端 JavaScript 中三種 for 循環(huán)語(yǔ)句。
這大概是應用最廣的循環(huán)語(yǔ)句了吧,簡(jiǎn)單實(shí)用,且大多數時(shí)候性能還是在線(xiàn)的,唯一的缺點(diǎn)大概就是太普通,沒(méi)有特色,導致很多人現在不愿用它。
const array = [4, 7, 9, 2, 6]; for (let index = 0; index < array.length; index++) { const element = array[index]; console.log(element); } // 4, 7, 9, 2, 6
for...in 語(yǔ)句可以以任意順序遍歷一個(gè)對象的除 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() 或執行 hasOwnProperty() 來(lái)確定某屬性是否是對象本身的屬性。
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
當然,也可以用來(lái)遍歷數組。
const arr = [1, 2, 3, 4, 5]; for (const key in arr) { console.log(key) } // 0,1,2,3,4
使用 for...in 可以遍歷數組,但是會(huì )存在以下問(wèn)題:
所以一般不建議使用 for...in 來(lái)遍歷數組。
for...of 語(yǔ)句在可迭代對象(包括 Array,Map,Set,String,TypedArray,arguments 對象等等)上創(chuàng )建一個(gè)迭代循環(huán),調用自定義迭代鉤子,并為每個(gè)不同屬性的值執行語(yǔ)句。
const array = ['a', 'b', 'c']; for (const element of array) { console.log(element); } // a // b // c
for...of 和 for...in 的區別:
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 結構:
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 結構還是挺方便的,推薦使用!
到此這篇關(guān)于JavaScript中三種for循環(huán)語(yǔ)句使用總結的文章就介紹到這了,更多相關(guān)JS中for循環(huán)語(yǔ)句內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站