JavaScript中的遍歷詳解
編程這么多年,要是每次寫(xiě)遍歷代碼時(shí)都用 for 循環(huán),真心感覺(jué)對(duì)不起 JavaScript 語(yǔ)言~
對(duì)象遍歷
為了便于對(duì)象遍歷的測(cè)試,我在下面定義了一個(gè)測(cè)試對(duì)象 obj
。
測(cè)試對(duì)象
// 為 Object 設(shè)置三個(gè)自定義屬性(可枚舉)
Object.prototype.userProp = 'userProp';
Object.prototype.getUserProp = function() {
return Object.prototype.userProp;
};
// 定義一個(gè)對(duì)象,隱式地繼承自 Object.prototype
var obj = {
name: 'percy',
age: 21,
[Symbol('symbol 屬性')]: 'symbolProp',
unEnumerable: '我是一個(gè)不可枚舉屬性',
skills: ['html', 'css', 'js'],
getSkills: function() {
return this.skills;
}
};
// 設(shè)置 unEnumerable 屬性為不可枚舉屬性
Object.defineProperty(obj, 'unEnumerable', {
enumerable: false
});
ES6 之后,共有以下 5 種方法可以遍歷對(duì)象的屬性。
for…in: 遍歷對(duì)象自身的和繼承的可枚舉屬性(不含 Symbol 類(lèi)型的屬性)
for (let key in obj) {
console.log(key);
console.log(obj.key); // wrong style
console.log(obj[key]); // right style
}
不要使用 for…in 來(lái)遍歷數(shù)組,雖然可以遍歷,但是如果為 Object.prototype 設(shè)置了可枚舉屬性后,也會(huì)把這些屬性遍歷到,因?yàn)閿?shù)組也是一種對(duì)象。
Object.keys(obj):返回一個(gè)數(shù)組,包括對(duì)象自身的(不含繼承的)所有可枚舉屬性(不含 Symbol 類(lèi)型的屬性)
Object.keys(obj);
// ["name", "age", "skills", "getSkills"]
Object.getOwnPropertyNames(obj);
// ["name", "age", "unEnumerable", "skills", "getSkills"]
Object.getOwnPropertySymbols(obj);
// [Symbol(symbol 屬性)]
Reflect.ownKeys(obj);
// ["name", "age", "unEnumerable", "skills", "getSkills", Symbol(symbol 屬性)]
以上的5種方法遍歷對(duì)象的屬性,都遵守同樣的屬性遍歷的次序規(guī)則
- 首先遍歷所有屬性名為數(shù)值的屬性,按照數(shù)字排序
- 其次遍歷所有屬性名為字符串的屬性,按照生成時(shí)間排序
- ***遍歷所有屬性名為Symbol值的屬性,按照生成時(shí)間排序
如何判斷某個(gè)屬性是不是某個(gè)對(duì)象自身的屬性呢?
用 in 操作符(不嚴(yán)謹(jǐn),它其實(shí)判定的是這個(gè)屬性在不在該對(duì)象的原型鏈上)
'age' in obj; // true
'userProp' in obj; // true (userProp 是 obj 原型鏈上的屬性)
'name' in Object; // true
// 上面這個(gè)也是 true 的原因是,Object 是一個(gè)構(gòu)造函數(shù),而函數(shù)恰巧也有一個(gè) name 屬性
Object.name; // 'Object'
Array.name; // 'Array'
obj.hasOwnProperty('age'); // true
obj.hasOwnProperty('skills'); // true
obj.hasOwnProperty('userProp'); // false
// 利用 Object.create() 新建一個(gè)對(duì)象,并且這個(gè)對(duì)象沒(méi)有任何原型鏈
var obj2 = Object.create(null, {
name: { value: 'percy' },
age: { value: 21 },
skills: { value: ['html', 'css', 'js'] }
});
obj2.hasOwnProperty('name'); // 報(bào)錯(cuò)
obj2.hasOwnProperty('skills'); // 報(bào)錯(cuò)
針對(duì)上面的情況,我們用一個(gè)更完善的解決方案來(lái)解決。
使用 Object.prototype.hasOwnProperty.call(obj,’prop’…)
Object.prototype.hasOwnProperty.call(obj2,'name'); // true
Object.prototype.hasOwnProperty.call(obj2,'skills'); // true
Object.prototype.hasOwnProperty.call(obj2,'userProp'); // false
數(shù)組遍歷
數(shù)組實(shí)際上也是一種對(duì)象,所以也可以使用上面對(duì)象遍歷的任意一個(gè)方法(但要注意尺度),另外,數(shù)組還擁有其他遍歷的方法。
- 最基本的 for 循環(huán)、while 循環(huán)遍歷(缺陷是多添加了一個(gè)計(jì)數(shù)變量)
- ES6 引入:for…of ,這下就沒(méi)有這個(gè)計(jì)數(shù)變量了,但是也不夠簡(jiǎn)潔(這里不做詳細(xì)介紹,以后寫(xiě))
for(let value of arr){
console.log(value);
}
下面說(shuō)幾種數(shù)組內(nèi)置的一些遍歷方法
Array.prototype.forEach(): 對(duì)數(shù)組的每個(gè)元素執(zhí)行一次提供的函數(shù)
Array.prototype.forEach(callback(currentValue, index, array){
// do something
}[,thisArg]);
// 如果數(shù)組在迭代時(shí)被修改了,則按照索引繼續(xù)遍歷修改后的數(shù)組
var words = ["one", "two", "three", "four"];
words.forEach(function(word) {
console.log(word);
if (word === "two") {
words.shift();
}
});
// one
// two
// four
Array.prototype.map(callback(currentValue, index, array){
// do something
}[,thisArg]);
``` ```js
// map 的一個(gè)坑
[1,2,3].map(parseInt); // [1, NaN, NaN]
// 提示 map(currentValue,index,array)
// parseInt(value,base)
- Array.prototype.every(callback[,thisArg]): 測(cè)試數(shù)組的各個(gè)元素是否通過(guò)了回調(diào)函數(shù)的測(cè)試,若都通過(guò),返回 true,否則返回 false(說(shuō)地本質(zhì)點(diǎn)兒,就是如果回調(diào)函數(shù)每次返回的值都是 true 的話(huà),則 every() 返回 true,否則為 false)
- Array.prototype.filter(callback[,thisArg]): 返回一個(gè)新數(shù)組,數(shù)組的元素是原數(shù)組中通過(guò)測(cè)試的元素(就是回調(diào)函數(shù)返回 true 的話(huà),對(duì)應(yīng)的元素會(huì)進(jìn)入新數(shù)組)
- Array.prototype.find(callback[,thisArg]): 返回***個(gè)通過(guò)測(cè)試的元素
- Array.prototype.findIndex(callback[,thisArg]): 與上面函數(shù)類(lèi)似,只不過(guò)這個(gè)是返回索引
- Array.prototype.some(callback[,thisArg]): 類(lèi)似 find() ,只不過(guò)它不返回元素,只返回一個(gè)布爾值。只要找到一個(gè)通過(guò)測(cè)試的,就返回 true
- Array.prototype.reduce(callback,[initialValue]): 習(xí)慣性稱(chēng)之為累加器函數(shù),對(duì)數(shù)組的每個(gè)元素執(zhí)行回調(diào)函數(shù),***返回一個(gè)值(這個(gè)值是***一次調(diào)用回調(diào)函數(shù)時(shí)返回的值)
- 這個(gè)函數(shù)的回調(diào)函數(shù)有 4 個(gè)參數(shù)
- accumulator: 上一次調(diào)用回調(diào)函數(shù)返回的值
- currentValue: 當(dāng)前在處理的值
- currentIndex
- array
- initialValue: 可選項(xiàng),其值用于***次調(diào)用 callback 的***個(gè)參數(shù)
- 這個(gè)函數(shù)的回調(diào)函數(shù)有 4 個(gè)參數(shù)
- Array.prototype.reduceRight(callback[, initialValue]): 用法和上面的函數(shù)一樣,只不過(guò)遍歷方向正好相反
// 一些相關(guān)的案例
// 對(duì)數(shù)組進(jìn)行累加、累乘等運(yùn)算
[1,10,5,3,8].reduce(function(accumulator,currentValue){
return accumulator*currentValue;
}); // 1200
// 數(shù)組扁平化
[[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
}); // [0, 1, 2, 3, 4, 5]
[[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
return a.concat(b);
}); // [4, 5, 2, 3, 0, 1]
總結(jié)一下上面這些函數(shù)的共性
- 都是通過(guò)每次的回調(diào)函數(shù)的返回值進(jìn)行邏輯操作或判斷的
- 回調(diào)函數(shù)都可以寫(xiě)成更簡(jiǎn)潔的箭頭函數(shù)(推薦)
- 都可以通過(guò)形如 Array.prototype.map.call(str,callback) 的方式來(lái)操作字符串
var str = '123,hello';
// 反轉(zhuǎn)字符串
Array.prototype.reduceRight.call(str,function(a,b){
return a+b;
}); // olleh,321
// 過(guò)濾字符串,只保留小寫(xiě)字母
Array.prototype.filter.call('123,hello', function(a) {
return /[a-z]/.test(a);
}).join(''); // hello
// 利用 map 遍歷字符串(這個(gè)例子明顯舉得不太好 *_*)
Array.prototype.map.call(str,function(a){
return a.toUpperCase();
}); // ["1", "2", "3", ",", "H", "E", "L", "L", "O"]
最下面的文章想說(shuō)的就是讓我們用更簡(jiǎn)潔的語(yǔ)法(比如內(nèi)置函數(shù))遍歷數(shù)組,從而消除循環(huán)結(jié)構(gòu)。