max = numbers.reduce( (acc, val) => acc > val ? acc: val);
// max = 255
5.18.3
讨论
reduce()
方法看起来比其他函数式数组处理方法要复杂,例如
map()
(
5.17
节)、
filter()
(
5.9
节)或
sort()
(
5.16
节)。与另几个函数式方法相比,
reduce()
方
法的不同点在于,你要想办法存储每次调用回调函数得到的数据。注意,你可以使
用累加器存储一个自定义的对象,通过多个属性记录多个信息。归约函数还接受两
个可选的参数:
index
(当前元素的索引)和
array
(归约计算的整个数组)。但是
请小心,过度使用
reduce()
方法的代码容易让人难以理解。
5.18.4
参考
找出数组中最大的数还有一种方式。你可以使用
Math.max()
方法,通过展开运算
符把数组变成传入的一系列参数(见
5.5
节)。
5.19
验证数组内容
5.19.1
问题
你想确保数组内容满足特定的条件。
5.19.2
方案
使用
Array.every()
方法检查是否每个元素都能通过指定的测试。例如,下述代码
使用正则表达式确保数组中的每个元素都只包含字母符号。
//
执行测试的函数 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.