创建函数 johnLennonFacts。
此函数将接受一个参数,即一组有关约翰·列侬的事实(请注意,它可能不完全是以下事实):
const facts = [
"He was the last Beatle to learn to drive",
"He was never a vegetarian",
"He was a choir boy and boy scout",
"He hated the sound of his own voice"
];
使用 while 循环遍历事实数组并添加“!!!”直到每一个事实的结束。 返回带有感叹号的字符串数组。
function johnLennonFacts(array) {
let i = 0;
while (i < (0, array.length, i++)) {
array.push('!!!');
}
return array;
}
我不断返回原始数组,但我需要通过 while 循环向它们添加解释点。
最佳答案
您需要串联
而不是push
,即push
向数组添加一个新元素,而您所需的输出需要添加(串联)!!!
在元素末尾,因此使用字符串连接
const facts = [
"He was the last Beatle to learn to drive",
"He was never a vegetarian",
"He was a choir boy and boy scout",
"He hated the sound of his own voice"
];
const final = facts.map(e=> e + '!!!')
console.log(final)
你原来的代码可以改为
function johnLennonFacts(array) {
let i = 0;
let newArray = []
while (i < array.length) {
newArray.push(array[i] + ' !!!')
i++
}
return newArray;
}
const facts = [
"He was the last Beatle to learn to drive",
"He was never a vegetarian",
"He was a choir boy and boy scout",
"He hated the sound of his own voice"
];
console.log(johnLennonFacts(facts))
关于javascript - 有没有办法将字符串推到数组中每个元素的末尾(我必须使用 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56635943/