[英]How can i save a reference to an Array method?
有沒有辦法實現這種行為?
提前致謝。
const filterBy = (arr, side) => {
const reduceFunc = side === 'left' ? reduce : reduceRight;
arr.reduceFunc(...)
}
是的,您只需要獲取一個字符串,然后使用括號符號即可訪問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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.