使用扩展语法而不是 for 循环

Use spread syntax instead of for loop

我想使用扩展语法来减少此代码以删除 for 循环,有什么想法吗?

function shiftChar() {
  let aCharArray = prompt("Enter a word").split("");
  for (let i = 0; i < aCharArray.length; i++) {
    aCharArray[i] = String.fromCharCode(aCharArray[i].charCodeAt(0) + 1);
  }
  alert(aCharArray);
}

这行不通

function shiftChar() {
  let aCharArray = prompt("Enter a word").split("");
  aCharArray = String.fromCharCode(...aCharArray.charCodeAt(0) + 1);
  alert(aCharArray);
}

不使用传播的缩小解决方案:

function shiftChar() {
    alert(
      prompt("Enter a word").split("")
      .map(letter => String.fromCharCode(letter.charCodeAt(0) + 1));
    );
}

使用传播的(奇怪的)缩小解决方案:

function shiftChar() {
    alert(
      [...prompt("Enter a word")].map(letter => ( 
        String.fromCharCode(letter.charCodeAt(0) + 1)
      )
    );
}

对于数组中的每个元素,您都在进行一些操作,charCodeAt(0) + 1,因此最好使用 map

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

您可以使用 spread syntax 从数组中更新变量 aCharArray 的内容。

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments

function shiftChar() {
  let aCharArray = prompt("Enter a word").split("").map(x => x.charCodeAt(0) + 1);
  aCharArray = String.fromCharCode(...aCharArray);
  alert(aCharArray);
}

扩展语法 (!) is not a replacement for loops, it's a replacement for apply.

你可以做到

const string = prompt("Enter a word");
const charCodes = [];
for (let i = 0; i < aCharArray.length; i++) {
    aCharCodes[i] = aString.charCodeAt(i) + 1;
}

虽然然后使用

String.fromCharCode(...charCodes)

而不是

String.fromCharCode.apply(String, charCodes)