简体   繁体   English

将普通函数转换为箭头函数

[英]Convert normal function to arrow function

I am trying to convert the below function into arrow function using ES6, 我正在尝试使用ES6将以下功能转换为箭头功能,

$scope.sum = function(list, prop){
  return list.reduce( function(a, b){
     return a + b[prop];
  }, 0);
};

I tried below, 我在下面尝试过

$scope.sum = (list,prop) =>  {return list.reduce((a,b) => {return (a+ b[prop])}, 0)};

throwing this error Cannot read property 'reduce' of undefined 抛出此错误Cannot read property 'reduce' of undefined

i am using in angular 1.5 我在angular 1.5中使用

Your two functions are identical. 您的两个功能是相同的。

const sum1 = function(list, prop){ return list.reduce( function(a, b){ return a + b[prop];}, 0);};

const sum2 = (list,prop) =>  { return list.reduce((a,b) => {return (a+ b[prop])}, 0)};

const list = [{foo:1},{foo:2},{foo:3}]

console.log(sum1(list, 'foo'));
console.log(sum2(list, 'foo'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM