let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
或
let id = Math.max(...items.map(item => item.id).concat(0)); // concat(0) for empty array
// slimmer and sleeker ;)
let id = Math.max(...items.map(item => item.id), 0);
这种方式比较实用,因为在空数组的情况下,返回0,不像
Math.max.apply(null, [].map(item => item.id)) // -Infinity
如果你想得到“自动增量”,你可以加1,不管数组是否为空
// starts at 1 if our array is empty
autoincrement = items.reduce((maxId, item) => Math.max(maxId, item.id), 0) + 1;
UPD: 使用 map 的代码更短,但使用 reduce 更快,这是大型数组所感受到的
let items = Array(100000).fill()
.map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
const n = 100;
console.time('reduce test');
for (let i = 1; i < n; ++i) {
let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
}
console.timeEnd('reduce test');
console.time('map test');
for (let i = 1; i < n; ++i) {
let id = Math.max(items.map(item => item.id).concat(0));
}
console.timeEnd('map test');
console.time('map spread test');
for (let i = 1; i < n; ++i) {
let id = Math.max(...items.map(item => item.id), 0);
}
console.timeEnd('map spread test');
减少测试:163.373046875ms
地图测试:1282.745849609375ms
地图传播测试:242.4111328125ms
如果我们创建一个更大的数组,spread map 将关闭
let items = Array(200000).fill()
.map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
减少测试:312.43896484375ms
地图测试:2941.87109375ms
未捕获的 RangeError:超出最大调用堆栈大小
在:15:32