From 1b70fc3777c7a37284c40ec2e96d42c72631c7b1 Mon Sep 17 00:00:00 2001 From: dp~ <457509824@qq.com> Date: Mon, 23 Oct 2017 22:48:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B0=E7=BB=84.find=20&&=20.findIndex=20&&?= =?UTF-8?q?=20.some=20&&=20=E3=80=82every?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 10.array-methods.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 10.array-methods.md diff --git a/10.array-methods.md b/10.array-methods.md new file mode 100644 index 0000000..d7feb5f --- /dev/null +++ b/10.array-methods.md @@ -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 +```