编程这么多年,要是每次写遍历代码时都用 for 循环,真心感觉对不起 JavaScript 语言~
为了便于对象遍历的测试,我在下面定义了一个测试对象 obj 。
- // 为 Object 设置三个自定义属性(可枚举)
- Object.prototype.userProp = 'userProp';
- Object.prototype.getUserProp = function(){
- return Object.prototype.userProp;
- };
- // 定义一个对象,隐式地继承自 Object.prototype
- var obj = {
- name: 'percy',
- age: 21,
- [Symbol('symbol 属性')]: 'symbolProp',
- unEnumerable: '我是一个不可枚举属性',
- skills: ['html', 'CSS', 'js'],
- getSkills: function(){
- return this.skills;
- }
- };
- // 设置 unEnumerable 属性为不可枚举属性
- Object.defineProperty(obj, 'unEnumerable', {
- enumerable: false
- });
ES6 之后,共有以下 5 种方法可以遍历对象的属性。
- for (let key in obj) {
- 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' in obj; // true
- 'userProp' in obj; // true (userProp 是 obj 原型链上的属性)
- 'name' in Object; // true
- // 上面这个也是 true 的原因是,Object 是一个构造函数,而函数恰巧也有一个 name 属性
- Object.name; // 'Object'
- Array.name; // 'Array'
- obj.hasOwnProperty('age'); // true
- obj.hasOwnProperty('skills'); // true
- obj.hasOwnProperty('userProp'); // false
但是它还是有不足之处的。举例~
- // 利用 Object.create() 新建一个对象,并且这个对象没有任何原型链
- var obj2 = 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]);
- // 如果数组在迭代时被修改了,则按照索引继续遍历修改后的数组
- 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 的一个坑
- [1,2,3].map(parseInt); // [1, NaN, NaN]
- // 提示 map(currentValue,index,array)
- // parseInt(value,base)
- // 一些相关的案例
- // 对数组进行累加、累乘等运算
- [1,10,5,3,8].reduce(function(accumulator,currentValue){
- return accumulator*currentValue;
- }); // 1200
- // 数组扁平化
- [[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]
总结一下上面这些函数的共性
- var str = '123,hello';
- // 反转字符串
- Array.prototype.reduceRight.call(str,
- function(a, b) {
- return a + b;
- }); // olleh,321
- // 过滤字符串,只保留小写字母
- Array.prototype.filter.call('123,hello',
- function(a) {
- return /[a-z]/.test(a);
- }).join(''); // hello
- // 利用 map 遍历字符串(这个例子明显举得不太好 *_*)
- Array.prototype.map.call(str,
- function(a) {
- return a.toUpperCase();
- }); // ["1", "2", "3", ",", "H", "E", "L", "L", "O"]
最下面的文章想说的就是让我们用更简洁的语法(比如内置函数)遍历数组,从而消除循环结构。
来源: http://www.open-open.com/lib/view/open1489565554091.html