## 数组使用
> 数组合并
ES5的写法
```
let arr1=[0,1,2];
let arr2=[3,4,5];
Array.prototype.push.apply(arr1,arr2);
```
ES6的写法
```
let arr3=['a','b','c'];
let arr4=[3,4,5];
arr3.push(...arr4);
```
> 几个属性的理解
- Object.keys(obj) :返回对象自身的所有可枚举的属性的键名
```
let arr1keys = Object.keys(arr1); // ["0", "1", "2", "3", "4", "5"]
let arr3keys = Object.keys(arr3); // ["0", "1", "2", "3", "4", "5"]
```
- Object.getOwnPropertyNames(obj):返回一个数组,包含对象自身的所有属性
```
let temp1 = Object.getOwnPropertyNames(arr1);// ["0", "1", "2", "3", "4", "5", "length"]
```
- Object.getOwnPropertySymbols(obj):返回一个数组,包含对象自身的所有Symbol属性
```
let temp2 = Object.getOwnPropertySymbols(arr2);// []
```
> for...of 、for...in 和 forEach
- for of是遍历键值
```
for( let i of arr3 ){
console.log(i);// a b c 3 4 5
}
```
- for...in循环:只遍历对象自身的和继承的可枚举的属性、for in是遍历键名
```
for( let i in arr3 ){
console.log(i);// 0 1 2 3 4 5
}
```
- forEach循环
```
arr3.forEach(function(item,index){
console.log(item);// a b c 3 4 5
console.log(index);// 0 1 2 3 4 5
});
```
> 数组过滤
- 扩展数组`prototype`属性过滤数组
```
let arrayAll = [{'id':'111','name':'aaa'},
{'id':'222','name':'bbb'},
{'id':'333','name':'ccc'}];
let arrayDel = [{'id':'111','name':'aaa'}];
Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (val.id == this[i].id) return i;
}
return -1;
};
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
for (let i of arrayDel.length) {
let obj = arrayDel[i];
array.remove(obj);
}
console.dir(array);
```
- lodash 库 `differenceBy` 方法
```
let newArray = differenceBy(array,[{'id':'111','name':'aaa'}],'id');
console.dir(newArray);
```
> ES 6 常用 `API`
![ES 6 常用方法](https://github.com/Boom618/ExceptionReadme/blob/master/image/9B89CB56DB8EDB991A2A17D1243D140B.png)
网友评论