弁言
在對數組或對象舉行遍用時,我們常常會運用到兩種要領:for...in
和 for...of
,那末這兩種要領之間的區分是什麼呢?讓我們來研討研討。
一、for…in
起首我們看下MDN對for...in
要領的詮釋:for…in | MDN
for…in 輪迴只遍歷可羅列屬性。像 Array和 Object運用內置組織函數所建立的對象都邑繼續自Object.prototype和String.prototype的不可羅列屬性,比方 String 的 indexOf() 要領或 Object的toString()要領。輪迴將遍歷對象自身的一切可羅列屬性,以及對象從其組織函數原型中繼續的屬性(更靠近原型鏈中對象的屬性掩蓋原型屬性)。
起首,我們簡樸的運用for...in
離別對對象和數組舉行遍歷:
// 遍歷對象
let obj = {
a: 1,
b: 2,
c: 3
};
for(let item in obj) {
console.log("item:" + item);
console.log(obj[item]);
}
// 運轉結果
item:a
1
item:b
2
item:c
3
// 遍曆數組
let arr = [1, 2, 3];
for(let item in arr) {
console.log("item:" + item);
console.log(arr[item]);
}
// 運轉結果
item:0
1
item:1
2
item:2
3
我們發明,運用for...in
舉行遍用時,item值為對象的key,為數組的index。
我們曉得,數組索引只是具有整數稱號的羅列屬性,而且與通用對象屬性雷同,因而不能保證for...in
以某種牢固的遞次返回索引,因而,不引薦運用for...in
舉行數組的遍歷。
下面,我們在上面代碼的基礎上,在arr數組上增添一個自定義屬性,再次遍歷,檢察結果。
arr.name = 'arrName';
for(let item in arr) {
console.log("item:" + item);
console.log(arr[item]);
}
// 運轉結果
item:0
1
item:1
2
item:2
3
item:name
arrName
我們發明,for...in
不僅會遍曆數組中的元素,還會遍歷自定義屬性。
二、for…of
說完for...in
我們再來看看for...of
,我們照樣先來看看MDN對其的詮釋 for…of | MDN
for…of語句在可迭代對象(包含 Array,Map,Set,String,TypedArray,arguments 對象等等)上建立一個迭代輪迴,挪用自定義迭代鈎子,併為每一個差別屬性的值實行語句。
一樣的,我們照樣運用與for...in
雷同的代碼舉行測試
// 遍歷對象
let obj = {
a: 1,
b: 2,
c: 3
};
for(let item of obj) {
console.log("item:" + item);
console.log(obj[item]);
}
// 運轉結果
for(let item of obj) {
^
TypeError: obj is not iterable
...
// 遍曆數組
let arr = [1, 2, 3];
for(let item of arr) {
console.log("item:" + item);
console.log(arr[item]);
}
// 運轉結果
item:1
undefined
item:2
undefined
item:3
undefined
我們能夠看出,運用for...of
對對象舉行遍用時,報了TypeError: obj is not iterable
毛病,對數組舉行遍用時,item直接是數組每一項的值。
我們再為arr增添自定義屬性,檢察結果。
arr.name = 'arrName';
for(let item in arr) {
console.log("item:" + item);
console.log(arr[item]);
}
// 運轉結果
item:1
undefined
item:2
undefined
item:3
undefined
for...of
沒有對數組的自定義屬性舉行遍歷。
三、總結
依據以上測試結果並參考了相干材料,我們得出了以下結論:
- 遍歷對象時引薦運用
for...in
,个中item為對象的key。運用for...of
會報錯。 - 遍曆數組時引薦運用
for...of
,个中item為數組每一項的值。運用for...in
則不能保證遍歷遞次且會遍歷出自定義屬性。 -
for...in
是ES5特徵,for...of
是ES6特徵,因而須要注重兼容性。 - 假如要運用
for...of
遍歷一般對象,須要合營Object.keys()
一同運用。
結束語
以上內容是我們對for...in
和for...of
的測試對照,在運用時記着其區分可更快的編寫代碼和排查毛病,若想相識其更深層區分,發起仔細瀏覽MDN相干材料。