2-13-数组的运用

一、some循环

平常使用的forEach是无法使用break和return中断的,如果想要强行让它中断,就需要抛出错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var BreakException = {};

try {

[1, 2, 3].forEach(function(el) {

console.log(el);

if (el === 2) throw BreakException;

});

} catch (e) {

if (e !== BreakException) throw e;

}

初次之外,我们还可以使用some

1
2
3
4
5
6
7
8
9
10
11
12
13
arr.some((item, index) => {

console.log('arr');

if (item == '苏大强') {

console.log(index);

return true;

}

});

二、every

判断数组中的state,如果为真则保留下来:

``
const arr = [

{ id: 1, name: ‘西瓜’, state: true },

{ id: 2, name: ‘榴莲’, state: false },

{ id: 3, name: ‘草莓’, state: true }

]

const result = arr.every(item => item.state);

console.log(result);

1
2
3
4
5

## 三、reduce

把数组中所有水果总价累加起来

const arr = [

{ id: 1, name: ‘西瓜’, state: true, price: 80, count: 1 },

{ id: 2, name: ‘榴莲’, state: false, price: 70, count: 2 },

{ id: 3, name: ‘草莓’, state: true, price: 60, count: 3 }

]

1
2
3

**第一种写法是:**

let amt = 0;

arr.filter(item => item.state).forEach(item => {

amt += item.price * item.count;

});

1
2
3

**第二种写法是:**

// reduce((‘累加的结果’, ‘当前项’) => { }, 初始值)

const result = arr.filter(item => item.state).reduce((amt, item) => {

return amt += item.price * item.count;

}, 0);

1
2
3

**简化写法:**

const result = arr.filter(item => item.state).reduce((amt, item) => amt
+= item.price * item.count, 0);



本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!