-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
数组.find && .findIndex && .some && 。every
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
``` |