for 循环 / 分配在 JavaScript 中



function encrypt(text, n) {
let odd = [];
let even = [];
let punc = [];

for(let i = 0; i < n; i++) {
text.split('').forEach((el,i,arr) => {
if(el === '!'||el === '.'||el ==='?'){
punc.push(el);
} else if(i % 2 === 0) {
odd.push(el);
} else {
even.push(el);
}
})
text = even.concat(odd).concat(punc).join('');
}
return text;
}
console.log(encrypt("This is a test!", 1));

您好,我正在尝试通过分隔每个字符来加密字符串输入,取每个第二个字符并将其放在前面,我将执行n次,这是另一个参数。

我现在遇到的麻烦是,如果我们需要加密的数字是 1,上面的代码运行良好,

"hsi  etTi sats!"

但从 2 开始,它确实工作得很奇怪。

当我输入这样的输入时,

console.log(encrypt("This is a test!", 2));

我期待

"s eT ashi tist!"

但是,由于某种原因,事实并非如此,我认为在我重新分配"文本"作为循环结果的语句中存在一些问题。我的想法是,如果我将结果重新分配为将再次通过循环的"文本",那么我将得到我想要的结果。但显然,这是错误的。

你能帮我理解为什么这种重新分配不能以我理解的方式工作吗?

您需要在每次迭代时将 3 个数组重置回空数组n.

...
text = even.concat(odd).concat(punc).join('');
odd = [];
even = [];
punc = [];
....

另外,您的if陈述是错误的:

if(el === '!'|'.'|'?')

应该是

if(el === '!'|| el === '.' || el === '?')

工作示例如下:

function encrypt(text, n) {
let odd = [];
let even = [];
let punc = [];
for(let i = 0; i < n; i++) {
text.split('').forEach((el,i,arr) => {
if(el === '!'|| el === '.' || el === '?'){
punc.push(el);
} else if(i % 2 === 0) {
odd.push(el);
} else {
even.push(el);
}
})
text = even.concat(odd).concat(punc).join('');
odd = [];
even = [];
punc = [];
}
return text;
}
console.log(encrypt("This is a test!", 1));
console.log(encrypt("This is a test!", 2));

最新更新