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

时间:2018-02-27 15:47:30

标签: javascript for-loop spread-syntax

我想使用扩展语法来删除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);
}

3 个答案:

答案 0 :(得分:3)

传播语法(it's not an operator!)不是循环的替代品,它可以替代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)

答案 1 :(得分:1)

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

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)
      )
    );
}

答案 2 :(得分:1)

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

  

map按顺序为数组中的每个元素调用一次提供的callback函数,并从结果中构造一个新数组。

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

  

扩展语法允许在零或多个参数的位置扩展数组表达式或字符串等可迭代

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