如何为下面给出的问题编写JavaScript程序?



编写一个接受三个(str, c, n)参数的函数。从'str'结尾开始。在每n个字符之后插入字符c ?

function three(str, c, n){
for(let i =0; i<str.length; i= i+n){
str.slice(i, i+n);
str = str + c;
}
return str;
}
console.log(three("apple", "c", 2));

我想,我用错方法了。

从'str'结尾开始。在每n个字符之后插入字符c ?

我认为这意味着字符串需要在更改后以c结束。如果我说错了请指正。

如果是这种情况,Array.prototype.reverse()和Array.prototype.map()可以提供帮助:

function three (str, c, n) {
return str.split('').reverse().map((currentValue, currentIndex, array) => {
if (currentIndex % n === 0) {
return currentValue + c
} else {
return currentValue
}
}).reverse().join('')
}
console.log(three("apple", "c", 2));

你可以这样做:

function three(str, c, n){
// split the string into an array
let letters = str.split('');
// copy to another array that will be the end result to avoid modifying original array
let result = [...letters];
// When we add to the array, it shift the next one and so on, so we need to account for that
let shift = 0;
// we go over each letter
letters.forEach((letter,index) => {
// if we are at the desired location
if(index > 0 && index % n == 0) {
// we add our letter at that location
result.splice(index+shift, 0, c);
// we increase shift by 1
shift++;
}
})
// we return the result by joining the array to obtain a string
return result.join('');
}
console.log(three("apple", "c", 2));//apcplce

这里,它不起作用,因为array# slice更新实际字符串,但返回一个新字符串。

返回数组部分的浅拷贝到从开始到结束选择的新数组对象

在我看来,解决这个问题最简单的方法是使用array# split方法将单词拆分为字符,如果索引匹配n参数,则将字符添加到每个项,最后重新连接数组

function three(str, c, n){
const strAsChar = str.split('')

return strAsChar.map((char, index) => (index - 1) % n === 0 ? 
char + c :
char
).join('')
}
console.log(three("apple", "c", 2));

最新更新