Converting ECMAScript 6's arrow function to a

2020-02-15 02:08发布

问题:

I have the following arrow function

if( rowCheckStatuses.reduce((a, b) => a + b, 0) ){}

rowCheckStatuses is an array of 1's and 0's, this arrow function adds them all up to produce a number. This number acts as a boolean to determine whether or not there is at least one "1" in the array.

The issue is, I don't really understand how arrow functions work, and my IDE thinks it's bad syntax and refuses to check the rest of my document for syntax errors.

How would I go about converting this to a regular function to alleviate both issues?

回答1:

You can refactor it as:

if( rowCheckStatuses.reduce(function(a, b){return a + b}, 0)

The initial accumulator isn't necessary (unless you expect the array to be empty sometimes), it could be:

if( rowCheckStatuses.reduce(function(a, b){return a + b})

This number acts as a boolean to determine whether or not there is at least one "1" in the array

It might be faster (and clearer) to use:

if( rowCheckStatuses.some(function(a){return a == 1}))

which will return true if there are any 1s in rowCheckStatuses and will return as soon as one is encountered. Another alternative is indexOf:

if( rowCheckStatuses.indexOf(1) != -1)

Lots of alternatives.



回答2:

An arrow function can usually be converted by replacing

(<args>) => <body>

with

function(<args>) { return <body>; }

So yours would be

rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0)

There are exceptions to this rule so it's important that you read up on arrow functions if you want to know all of the differences. You should also note that arrow functions have a lexical this.



回答3:

Replacing arrow functions with regular functions is usually unproblematic:

var f = x => y;
var g = function(x) { return y; }

Or, in your specific example:

rowCheckStatuses.reduce((a, b) => a + b, 0);
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0);

However, be aware of the exceptions:

Arrow functions don't bind a this value. Accessing this in an arrow function might thus return the value of the enclosing execution context's this:

function MyClass() {}
MyClass.prototype.f = () => this;
MyClass.prototype.g = function() { return this; }

myClass = new MyClass();
console.log(myClass.f()); // logs `Window`
console.log(myClass.g()); // logs `myClass`

Arrow functions also don't have access to a local arguments object. Accessing arguments in an arrow function might e. g. return the arguments of an enclosing function:

function test() {

  var f = () => arguments;
  var g = function() { return arguments; }
  
  console.log(f()); // logs test's arguments
  console.log(g()); // logs g's arguments
}

test('x');

The same holds for new.target and super. See also What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?