1. 求和sum
根据传入的参数, 将arguments类数组对象转化为真数组, 并利用reduce方法求和
function sum() {
// Array.from()将arguments类数组转换为真数组
// 也可以使用Array.prototype.slice.call(arguments) , 这是ES5语法, 兼容性更好
return Array.from(arguments).reduce((prev, cur) => {
return prev + cur
}, 0)
}
console.log(sum(1,2,3,4,5,6)); // 21
2. 去重
1. 简单的数组去重
function unique(array) {
// 亦可以直接return [...new Set(array)],彻底的ES6语法
return Array.from(new Set(array))
}
console.log(unique([1,2,2,3,3,5])); // [1, 2, 3, 5]
2. 稍微复杂点的数组去重
function reduceArray(array) {
if (array.length === 0) {
return []
}
let obj = {}
return array.reduce((cur, next) => {
obj[next.code] ? '' : obj[next.code] = true && cur.push(next)
return cur
}, [])
}
let array1 = [
{
code: '111',
name: 'lala'
},
{
code: '123',
name: 'aiai'
},
{
code: '111',
name: 'lala'
},
{
code: '131',
name: 'mimi'
}
]
console.log(reduceArray(array1));
3. 递增数组
function range(ends) {
return Array.from({length: ends}, (_, i) => i + 1)
}
console.log(range(3)); // [1, 2, 3]