属性的遍历
ES6一共有5种方法可以遍历对象的属性。
(1)for…in
for…in循环遍历对象自身的和继承的可枚举属性(不含Symbol属性)。
(2)Object.keys(obj)
Object.keys返回一个数组,包括对象自身的(不含继承的)所有可枚举属性(不含Symbol属性)。
(3)Object.getOwnPropertyNames(obj)
Object.getOwnPropertyNames返回一个数组,包含对象自身的所有属性(不含Symbol属性,但是包括不可枚举属性)。
(4)Object.getOwnPropertySymbols(obj)
Object.getOwnPropertySymbols返回一个数组,包含对象自身的所有Symbol属性。
(5)Reflect.ownKeys(obj)
Reflect.ownKeys返回一个数组,包含对象自身的所有属性,不管是属性名是Symbol或字符串,也不管是否可枚举。
以上的5种方法遍历对象的属性,都遵守同样的属性遍历的次序规则。
首先遍历所有属性名为数值的属性,按照数字排序。
其次遍历所有属性名为字符串的属性,按照生成时间排序。
最后遍历所有属性名为Symbol值的属性,按照生成时间排序。
Reflect.ownKeys({ [Symbol()]:0, b:0, 10:0, 2:0, a:0 })
// ['2', '10', 'b', 'a', Symbol()]
上面代码中,Reflect.ownKeys方法返回一个数组,包含了参数对象的所有属性。这个数组的属性次序是这样的,首先是数值属性2和10,其次是字符串属性b和a,最后是Symbol属性。
数据结构的遍历:
一、Array:
ES5:
(1)Array.prototype.forEach(function(item,index,array){…})
(2)Array.prototype.map(function(value,index,array){…//return value,该值会被插入新数组})映射为一个新数组
(3)Array.prototype.some(function(item){…//条件})数组中某一项满足则停止执行,并且返回true
(4)Array.prototype.every(function(item){…//条件})数组中有一项不满足则停止执行,并且返回false.
(5)Array.prototype.filter(function(item){…//return true或者false})返回过滤后的新数组
(6)Array.prototype.indexOf(item)
(7)Array.prototype.lastIndexOf(item)
(8)Array.prototype.reduce(function (previous, current, index, array) {…return value//返回值作为下一次循环的previous的值})
(9)Array.prototype.reduceRight同上,但是index的初始值为array.length-1
ES6:
(1)Array.from(parameter),用的最多应该是将set转化为Array,或者将元素选择器的结果转化为数组
(2)Array.of(parameter)消除new Array(parameter)由于参数个数不同而出现的重载
(3)Array.prototype.copyWithin(target, start = 0, end = this.length)没想到有什么好用的
(4)Array.prototype.find(function(value, index, arr) {…//条件})找到第一个返回值为true的成员
(5)Array.prototype.findIndex(function(value.index,arr){…//条件})作用同上,返回index
(6)Array.prototype.keys()获取键名遍历器
(7)Array.prototype.values()获取键值遍历器
(8)Array.prototype.entries()获取键值对遍历器
二、Set数据结构
该数据结构更新或创建时会去重,类似===但是在这里NAN和NAN是相等的
(1)Set.prototype.add(parameter)
(2)Set.prototype.delete(parameter)
(3)Set.prototype.has(parameter)
(4)Set.prototype.clear()
(5)Set.prototype.keys()返回键名的遍历器
(6)Set.prototype.values()返回键值遍历器
(7)Set.prototype.entries()返回键值对遍历器
(8)Set.prototype.forEach(function(value.key,set){})遍历
三、Map数据结构
键值对的集合,但是键名可以为对象,当键名为对象时判断他的内存地址相同则认为键名相同
(1)Map.prototype.set(key,value)
(2)Map.prototype.get(key)
(3)Map.prototype.has(key)
(4)Map.prototype.delete(key)
(5)Map.prototype.clear()
(6)Map.prototype.keys()
(7)Map.prototype.values()
(8)Map.prototype.entries()
(9)Map.prototype.forEach(function(value,key,map){…})