這篇文章主要講解了“JavaScript中怎么使用for循環語句”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“JavaScript中怎么使用for循環語句”吧!
這大概是應用最廣的循環語句了吧,簡單實用,且大多數時候性能還是在線的,唯一的缺點大概就是太普通,沒有特色,導致很多人現在不愿用它。
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 語句可以以任意順序遍歷一個對象的除 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() 來確定某屬性是否是對象本身的屬性。
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
當然,也可以用來遍歷數組。
const arr = [1, 2, 3, 4, 5]; for (const key in arr) { console.log(key) } // 0,1,2,3,4
使用 for...in 可以遍歷數組,但是會存在以下問題:
index 索引為字符串型數字(注意,非數字),不能直接進行幾何運算。
遍歷順序有可能不是按照實際數組的內部順序(可能按照隨機順序)。
所以一般不建議使用 for...in 來遍歷數組。
for...of 語句在可迭代對象(包括 Array,Map,Set,String,TypedArray,arguments 對象等等)上創建一個迭代循環,調用自定義迭代鉤子,并為每個不同屬性的值執行語句。
const array = ['a', 'b', 'c']; for (const element of array) { console.log(element); } // a // b // c
for...of 和 for...in 的區別:
for...in 語句以任意順序迭代對象的可枚舉屬性。
for...of 語句遍歷可迭代對象定義要迭代的數據。
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 結構還是挺方便的,推薦使用!
感謝各位的閱讀,以上就是“JavaScript中怎么使用for循環語句”的內容了,經過本文的學習后,相信大家對JavaScript中怎么使用for循環語句這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。