javascript - 有没有办法将字符串推送到数组中每个元素的末尾(我必须使用 while 循环?
问题描述
创建一个函数 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 循环向它们添加解释点。
解决方案
您不需要concatenation
,push
即向push
数组添加一个新元素,而您所需的输出需要!!!
在元素末尾添加(连接),所以使用string concatenation
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))
推荐阅读
- node.js - Firebase 功能因存档的“无法处理响应”而失败
- c++ - 在 C++ 中,为什么这个自定义哈希函数很慢?
- c# - 如何在 NET XML 文档注释中设置 XML 代码
- c# - 在c#中将3个整数列表转换为二维数组
- c - C程序没有输出
- javascript - 单击按钮时在 json 文件中切换真假
- javascript - 树多选下拉自动完成搜索框
- html - 内容安全策略:页面设置阻止在 http://127.0.0.1:8000/favicon.ico (“default-src”) 加载资源
- python - Numpy:比较两个数组并创建一个掩码
- javascript - 在 AWS 问题上部署 PRN 堆栈