Skip to content

Commit

Permalink
数组.find && .findIndex && .some && 。every
Browse files Browse the repository at this point in the history
  • Loading branch information
dptms committed Oct 23, 2017
1 parent f84592a commit 1b70fc3
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 10.array-methods.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# 更多 `Array` 方法使用
```
const inventory = [
{ name: 'apples', quantity: 2 },
{ name: 'bananas', quantity: 0 },
{ name: 'cheeries', quantity: 3 }
];
```

* .find()
返回找到的元素,参数传入一个回调函数,函数里面三个参数分别是 `element`,`index`,`array`

如果要在数组中寻找某个元素,可以使用循环,但是 `forEach` 中途不能打断,性能相对劣,`for of`可读性相对劣

```
const bananas = inventory.find(fruit => fruit.name === 'bananas');
```

* .findIndex()
类似 `.find()`,区别在于返回的是元素的索引

```
const bananas = inventory.findIndex(fruit => fruit.name === 'bananas');
```

* .some()
数组满足测试函数条件,返回 `true`
```
const bananas = inventory.find(fruit => fruit.quantity > 0); // true
```

* .every()
数组满足所有测试函数条件,返回 `true`
```
const bananas = inventory.every(fruit => fruit.quantity > 0); // false
```

0 comments on commit 1b70fc3

Please sign in to comment.