blog.percymong.com/2017/03/14/javascript-traversal/
编程这么多年,要是每次写遍历代码时都用 for 循环,真心感觉对不起 JavaScript 语言~
对象遍历
为了便于对象遍历的测试,我在下面定义了一个测试对象 obj。
// 为 Object 设置三个自定义属性(可枚举)
Object.prototype.userProp = ‘userProp’;
Object.prototype.getUserProp = function(){
returnObject.prototype.userProp;
};
// 定义一个对象,隐式地继承自 Object.prototype
varobj = {
name: ‘percy’,
age: 21,
[Symbol(‘symbol 属性’)]: ‘symbolProp’,
unEnumerable: ‘我是一个不可枚举属性’,
skills: [‘html’,’css’,’js’],
getSkills: function(){
returnthis.skills;
}
};
// 设置 unEnumerable 属性为不可枚举属性
Object.defineProperty(obj,’unEnumerable’,{
enumerable: false
});
ES6 之后,共有以下 5 种方法可以遍历对象的属性。
for(let key inobj){
console.log(key);
console.log(obj.key);// wrong style
console.log(obj[key]); // right style
}
不要使用 for…in 来遍历数组,虽然可以遍历,但是如果为 Object.prototype 设置了可枚举属性后,也会把这些属性遍历到,因为数组也是一种对象。
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种方法遍历对象的属性,都遵守同样的属性遍历的次序规则
如何判断某个属性是不是某个对象自身的属性呢?
‘age’inobj;// true
‘userProp’inobj; // true (userProp 是 obj 原型链上的属性)
‘name’inObject;// true
// 上面这个也是 true 的原因是,Object 是一个构造函数,而函数恰巧也有一个 name 属性
Object.name; // ‘Object’
Array.name;// ‘Array’
obj.hasOwnProperty(‘age’);// true
obj.hasOwnProperty(‘skills’); // true
obj.hasOwnProperty(‘userProp’);// false
但是它还是有不足之处的。举例~
// 利用 Object.create() 新建一个对象js循环对象,并且这个对象没有任何原型链
varobj2 = Object.create(null,{
name: {value: ‘percy’},
age: {value: 21},
skills: {value: [‘html’,’css’,’js’]}
});
obj2.hasOwnProperty(‘name’);// 报错
obj2.hasOwnProperty(‘skills’);// 报错
针对上面的情况,我们用一个更完善的解决方案来解决。
Object.prototype.hasOwnProperty.call(obj2,’name’); // true
Object.prototype.hasOwnProperty.call(obj2,’skills’); // true
Object.prototype.hasOwnProperty.call(obj2,’userProp’);// false
数组遍历
数组实际上也是一种对象,所以也可以使用上面对象遍历的任意一个方法(但要注意尺度),另外,数组还拥有其他遍历的方法。
for(let value of arr){
console.log(value);
}
下面说几种数组内置的一些遍历方法
Array.prototype.forEach(callback(currentValue,index,array){
// do something
}[,thisArg]);
// 如果数组在迭代时被修改了,则按照索引继续遍历修改后的数组
varwords = [“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 的一个坑
[1,2,3].map(parseInt);// [1, NaN, NaN]
// 提示 map(currentValue,index,array)
//parseInt(value,base)
一些有用的数组内置方法(类似 map,回调函数的参数都是那 3 个)
Array.prototype.reduceRight(callback[, initialValue]): 用法和上面的函数一样,只不过遍历方向正好相反
// 一些相关的案例
// 对数组进行累加、累乘等运算
[1,10,5,3,8].reduce(function(accumulator,currentValue){
returnaccumulator*currentValue;
});// 1200
// 数组扁平化
[[0,1],[2,3],[4,5]].reduce(function(a,b){
returna.concat(b);
});// [0, 1, 2, 3, 4, 5]
[[0,1],[2,3],[4,5]].reduceRight(function(a,b){
returna.concat(b);
});// [4, 5, 2, 3, 0, 1]
总结一下上面这些函数的共性
varstr = ‘123,hello’;
// 反转字符串
Array.prototype.reduceRight.call(str,function(a,b){
returna+b;
});// olleh,321
// 过滤字符串js循环对象,只保留小写字母
Array.prototype.filter.call(‘123,hello’,function(a){
return /[a-z]/.test(a);
}).join(”);// hello
// 利用 map 遍历字符串(这个例子明显举得不太好 *_*)
Array.prototype.map.call(str,function(a){
returna.toUpperCase();
});// [“1”, “2”, “3”, “,”, “H”, “E”, “L”, “L”, “O”]
最下面的文章想说的就是让我们用更简洁的语法(比如内置函数)遍历数组,从而消除循环结构。
参考资料
觉得本文对你有帮助?请分享给更多人
关注「前端大全」,提升前端技能
限时特惠:本站每日持续更新海量设计资源,一年会员只需29.9元,全站资源免费下载
站长微信:ziyuanshu688