简体   繁体   English

在 Javascript 中使用 ECMAScript 6 特性; 什么时候使用粗箭头函数等?

[英]Making use of ECMAScript 6 features in Javascript; When to use fat arrow functions, etc.?

I'm doing the Udemy course ES6 Javascript: The Complete Developer's Guide Stephen Grider on my own.我正在自己学习 Udemy 课程ES6 Javascript: The Complete Developer's Guide Stephen Grider This course is my first exposure to javascript.本课程是我第一次接触 javascript。 It contains an interesting (to me) exercise on detecting balanced parentheses.它包含一个有趣的(对我来说)检测平衡括号的练习。 I wrote a function with the features I would expect, but I did not use fat arrow functions.我编写了一个具有我期望的功能的函数,但我没有使用粗箭头函数。 I probably did not use other ECMAScript 6 features that I could have used.我可能没有使用我可以使用的其他 ECMAScript 6 功能。 I would like any suggestions on improving my code.我想要关于改进我的代码的任何建议。

function balancedParens(inputString){
  const errMsg1 = 'ERROR: expression will NEVER be balanced';
  const errMsg2 = 'ERROR: unbalanced!';
  const successMsg = 'parens are balanced.';
  const chars = inputString.split("");
  let count = 0;
  for ( let i = 0; i < chars.length; ++i ) {
    if ( count < 0 ) { console.log(errMsg1); return false; }
    if ( chars[i] === "(" ) { ++count; }
    else if ( chars[i] === ")" ) { --count; }
  }
  if ( count < 0 ) { console.log(errMsg1); return false; }
  else if ( count == 0 ) { console.log(successMsg); return true; }
  else { console.log(errMsg2); return false; }
}

balancedParens("()()(i)"); //correctly returns true
balancedParens("()()())"); //correctly returns false

My function detects parens that can never be balanced and bails out early, which is something the example from the course did not do.我的函数检测到永远无法平衡的括号并提前退出,这是课程中的示例没有做到的。 I want to retain this feature as I refactor and improve my code.我想在重构和改进代码时保留此功能。

The course strongly recommends against using for-loops, but I couldn't think of a better way to implement my features.本课程强烈建议不要使用 for 循环,但我想不出更好的方法来实现我的功能。 And I couldn't see how using fat arrow functions would improve the code.而且我看不出使用粗箭头函数会如何改进代码。 So I am looking forward to suggestions and feedback.所以我期待着建议和反馈。

I think your code is fine.我认为你的代码很好。 It is straight-forward and easy to understand.它直截了当且易于理解。 However it is definitely not what the current javascript hipsters would think is cool or whatever.然而,它绝对不是当前的 javascript 时髦人士认为的酷或其他什么。

Unfortunately w/o using a traditional loop structure like a for loop, you cannot exit early when parens can never be balanced.不幸的是,如果不使用像 for 循环这样的传统循环结构,当括号永远无法平衡时,您无法提前退出。 So honestly your function is probably more efficient than what they're looking for.所以老实说,你的功能可能比他们正在寻找的更有效率。 But generally speaking javascript hipsters don't really care about code efficiency.但一般来说,javascript 时髦人士并不真正关心代码效率。

This might be more what they're looking for:这可能是他们正在寻找的更多:

 const balancedParens = inputString => // We don't need curly brackets here because we're doing everything // on one "line" and just returning inputString.split('') // Reduce is the substitute for your for loop here. // It iterates over each character and stores the return value in "sum" // on each iteration .reduce((sum, char) => { if (char === '(') return sum + 1; else if (char === ')') return sum - 1; else return sum; // This comparison makes the entire function return true if // our reduce resulted in zero, otherwise false }, 0) === 0; const logResult = result => result ? console.log('parens are balanced.') : console.log('ERROR: unbalanced!'); logResult(balancedParens('()()(i)')); logResult(balancedParens('()()())'));

If you're not familiar with the reduce function on the array, check it out here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce如果您不熟悉数组上的 reduce 函数,请在此处查看: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

It is a higher-order function (meaning a function that takes a function as one of it's arguments).它是一个高阶函数(意味着将函数作为其参数之一的函数)。 This is a common use case for the fat arrows simply because the notation ends up being much more terse.这是粗箭头的常见用例,因为符号最终变得更加简洁。

Note: I might be skeptical about any course that "strongly recommends against" for loops.注意:我可能会对“强烈建议反对”for 循环的任何课程持怀疑态度。 But maybe they're just trying to get you to use the new JS features.但也许他们只是想让你使用新的 JS 功能。

My personal opinion is that arrow functions work best when you do not have to bind this to the current function context.我个人的观点是,当您不必将this绑定到当前函数上下文时,箭头函数效果最好。 At this point this will not make any sense to you but arrow functions do not have their own this keyword which means the value of this will be taken outside the lexical scope of the arrow function.在这一点上,这对您没有任何意义,但箭头函数没有自己的this关键字,这意味着this的值将超出箭头函数的词法范围。 They are good for callbacks aswell( the same rule above applies ), also when you need to write a short expression, it looks neat.它们也适用于回调(上述规则适用),而且当您需要编写简短的表达式时,它看起来很整洁。 It all depends on you just make sure you know how this behaves and you will be ok.这一切都取决于你,只要确保你知道是如何表现的,你就会没事的。

Reduce function can be used to iterate over the string and return a single value. Reduce 函数可用于迭代字符串并返回单个值。 reduce 降低

Arrow functions are used for the lexical scoping of this.箭头函数用于 this 的词法范围。 Arrow functions 箭头函数

Upgradation of ES5 features- bind,call and apply. ES5 特性的升级——绑定、调用和应用。

 const errMsg1 = 'ERROR: expression will NEVER be balanced'; const errMsg2 = 'ERROR: unbalanced!'; const successMsg = 'parens are balanced.'; balancedParanthesis = (string) => { return string.split("").reduce((count, char) => { //returns boolean expression if(count < 0 ){return count;} else if(char === '('){++count;} else if(char === ')'){ --count;} return count; },0) } let count = balancedParanthesis("()()"); //let count = balancedParanthesis("((())"); //let count = balancedParanthesis(")((())"); if ( count < 0 ) { console.log(errMsg1); } else if ( count == 0 ) { console.log(successMsg); } else { console.log(errMsg2); }

I'm not sure on the context, but there's no reason to believe that for loops are inherantly bad.我不确定上下文,但没有理由相信 for 循环天生就不好。 You might want to be aware of the performance impact of nesting for loops but classical for loops are used often enough and there's no reason not to use them.您可能希望了解嵌套 for 循环对性能的影响,但经典 for 循环的使用已经足够频繁,因此没有理由不使用它们。

As far as arrow functions go, in your case the advantages might be that your code is more concise and easier to read.就箭头函数而言,在您的情况下,优点可能是您的代码更简洁且更易于阅读。 Arrow functions are just a shorthand way of writing functions.箭头函数只是编写函数的一种简写方式。 More often than not, readability is more important than the slim performance improvements you may or may not get from using arrow functions, streams and functional programming features provided in ES6.通常情况下,可读性比使用 ES6 中提供的箭头函数、流和函数式编程特性可能会或可能不会获得的微小性能改进更重要。

For your case, it might be nice to use some arrow functions to make your code more concise.对于您的情况,使用一些箭头函数使您的代码更简洁可能会很好。 So you could replace the for loop by streaming the char array and using .forEach .因此,您可以通过流式传输 char 数组并使用.forEach来替换 for 循环。

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

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