美文网首页
数组的遍历

数组的遍历

作者: BoomHe | 来源:发表于2017-01-11 14:57 被阅读16次

## 数组使用

> 数组合并

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)

相关文章

  • angular2foreach遍历的几种用法

    遍历简单的数组 遍历数组对象 遍历嵌套数组

  • foreach/forin

    1.for/in遍历属性,数组是遍历下标 for/each遍历属性值,数组遍历数组的值

  • VS常用四种遍历数组的方法

    目录 for 遍历数组 for in 遍历数组 for of 遍历数组 forEach遍历数组 优缺点总结原文:h...

  • JS数组遍历的三种常用方法

    1.数组下标遍历 数组下标遍历是最常用也最普通的数组遍历方式 例如: 2.for in遍历 for in是根据数组...

  • for_of循环

    for(let value of target){}循环遍历 遍历数组 遍历Set 遍历Map 遍历字符串 遍历伪数组

  • PHP中的数组

    数组分类 索引数组 关联数组 数组遍历 传值遍历 传址遍历 数组函数 指针操作函数 current($array)...

  • Go的数组和指针

    一、 定义数组 二、 遍历数组 下标遍历 range遍历(index) range遍历(index,value) ...

  • forEach、for-in与for-of的区别

    遍历数组推荐for of ,遍历对象推荐 for in for in可以用来便利数组和对象 for in在遍历数组...

  • 7.19

    数组-遍历 遍历:一次获取到数组中的每个元素 索引数组遍历 var arr = ["a","b","c","d"...

  • Java 数组的基本操作

    1.遍历数组 遍历数组就是获取数组中的每个元素。通常遍历数组都是使用for循环来实现。下面是遍历一个二维数组 2....

网友评论

      本文标题:数组的遍历

      本文链接:https://www.haomeiwen.com/subject/odlrbttx.html