有没有办法实现这种行为?
谢谢。
const filterBy = (arr, side) => {
const reduceFunc = side === 'left' ? reduce : reduceRight;
arr.reduceFunc(...)
}
答案 0 :(得分:3)
是的,您只需要获取一个字符串,然后使用括号表示法即可访问Array.prototype
上的相应函数:
const filterBy = (arr, side) => {
const propName = side === 'left' ? 'reduce' : 'reduceRight';
// silly minimal example, will simply return the last item that's iterated over:
return arr[propName]((a, item) => item);
}
const arr = [1, 2];
// Reduces starting from left, last item iterated over will be 2:
console.log(filterBy(arr, 'left'));
// Reduces starting from right, last item iterated over will be 1:
console.log(filterBy(arr, 'right'));