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