【问题标题】:Javascript - Rewriting for-loop using arrow functions?Javascript - 使用箭头函数重写 for 循环?
【发布时间】:2019-06-06 06:58:20
【问题描述】:

如何使用箭头函数重写它?

forEach 是唯一的方法吗?

什么是不使用箭头函数的示例 forEach 方法。

代码

let word = 'Bloc';

const reverseString = (str) => {

   let stack = [];

   for (let i of str) {

     stack.push(str[i]);

   }

   let reversed = '';

   for (let i of word) {

     reversed += stack.pop();

   }

  return reversed;

 }

console.log(reverseString('Bloc'));

【问题讨论】:

  • 您已经在代码中使用了箭头函数,并且您没有使用functions。没有非箭头函数可以转换为箭头函数。
  • 可能属于CodeReivew 但是……你想在这里重写什么?
  • 将 for 循环转换为箭头函数
  • 但这并不意味着

标签: javascript for-loop stack filtering arrow-functions


【解决方案1】:

您将使用Array.reduce 方法。 (在这种情况下,reduceRight)。

const str = 'helloworld'; 

const newStr = str.split('').reduceRight((acc, cur) => {
    return acc + cur; 
}, ''); 

console.log(newStr); 

【讨论】:

    【解决方案2】:

    在这种情况下,对于反向字符串,您还可以遵循以下代码:-

    let word = 'Bloc';
    
    const reverseString = (str) => {
      let reversed = '';
    
      // use split function of string to split and get array of letter and then call the reverse method of array and then join it .
      reversed = str.split('').reverse().join('');
    
      return reversed;
    
    }
    
    console.log(reverseString('Bloc'));

    【讨论】:

    • 这并不能真正回答问题 - 这是关于如何避免使用 for 循环的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2021-03-29
    • 2019-06-16
    相关资源
    最近更新 更多