Javascript 将修改后的数组返回到句子字符串中

Javascript 将修改后的数组返回到句子字符串中,javascript,arrays,string,Javascript,Arrays,String,我试图编辑(为了演示目的)任何东西传递的单词列表。在这之后,我想在将它传回时返回,但我一直在思考如何在编辑后将它作为一个数组中的一个句子返回。下面是我的代码 function funk(words){ let arr = words.split(" ") arr.forEach((e) =>{ console.log(`${e}...`); //returns in 2 lines but I want it same as I passed i.e

我试图编辑(为了演示目的)任何东西传递的单词列表。在这之后,我想在将它传回时返回,但我一直在思考如何在编辑后将它作为一个数组中的一个句子返回。下面是我的代码

function funk(words){
  let arr = words.split(" ")
  arr.forEach((e) =>{
        console.log(`${e}...`);
        //returns in 2 lines but I want it same as I passed i.e. A sentence or string
  })
}

funk("hello world")

您的问题是将数组返回到组合字符串,但您的注释是在同一行上进行输出。我们都不知道你想要什么

// After converting it, let's return it to a combined form
Array.prototype.back = function() {
    return this.join(' ').split('...').join('')
};
// Let's convert it to your format of ['Hello...', 'world...']
String.prototype.convert = function() {
    return this.split(' ').map(w => `${w}...`)
};

let b = 'Hello world'.convert();
let f = b.back();


console.log('Begin', b);
console.log('Final', f);
输出

对于同一行,使用你的函数。您在一个循环中使用了
forEach
,因此它将为循环中的每个元素注销控制台。这就是为什么它不在同一条线上。Node.JS示例您可以使用
process.stdout

function funk(words){
    let arr = words.split(" ")
    arr.forEach((e) =>{
        process.stdout.write(`${e}...`);
        // Will be one line
    })
    // Add this for trailing line console.log('\n');
}
输出(同一行)


进行更改后,您可以使用
返回arr.join(“”)

您需要以不同的方式修改数组,例如使用函数。您可以使用该函数重新加入阵列。以您的相同代码为例:

函数funk(单词){
设arr=words.split(“”)
arr=arr.map((e)=>{
return e+“!”;//您可以在此处对数组中的单词添加任何修改
})
//这将获取已修改的数组并将其放在一起,以分离其
//按空间排列的元素
返回arr.join(“”);
}

console.log(funk(“hello world”)//显示“hello!world!”
只需arr.joint(“”)…这是函数,您希望输出的字符串是“hello…world…”?@benvc这是一个示例@benvc我希望它与句子在同一行,或者类似于它在参数中的传递方式,但出现了更改。现在,如果你检查控制台,它会显示在2行上。我不知道这如何使它成为15分钟前@Raymond25这里被问到的问题的不好或不正确的答案,我发布了我的答案。我们每个人都在使用相同的映射功能和相同的技术。他显然不知道自己想要什么,所以让我们等到他编辑后再发布新答案,谢谢@benvc,我甚至没有检查其他答案哈哈,但没关系,我只是想帮助社区
function funk(words){
    let arr = words.split(" ")
    arr.forEach((e) =>{
        process.stdout.write(`${e}...`);
        // Will be one line
    })
    // Add this for trailing line console.log('\n');
}
hello...world...