我怎样才能把reverseString函数变成一个像sum这样的变量。有区别吗?

时间:2019-09-24 05:36:10

标签: javascript code-cleanup ecmascript-7

我想学习如何清理代码,我觉得可以将反向字符串函数转换为变量。这可能吗?

function reverseString(str) {
  return str.split('').reduce((revString, char) => char + revString, '');
}
const reverse = reverseString('Cornell');
console.log(reverse);


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);

2 个答案:

答案 0 :(得分:1)

为什么要减少?

"As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:"

console.log(
  'Cornell'.split("").reverse().join("")
)


// as a const:

const rev = str => str.split("").reverse().join("")
console.log(rev('Cornell'))

答案 1 :(得分:0)

const reverseStr = (str) => str.split('').reduce((revString, char) => char + 
revString, '');
console.log(reverseStr('Name'));