繁体   English   中英

如何在不使用.join()的情况下将数组转换为不带逗号的字符串并在javascript中用空格分隔?

[英]How to convert array into string without comma and separated by space in javascript without using .join()?

我正在尝试寻找.join()的替代方法。 我要删除“,”并添加一个空格。 这是myArray的期望输出:嘿,

 // create a function that takes an array and returns a string // can't use join() // create array const myArray = ["Hey", "there"]; /** * * @param {Array} input * @returns {String} */ const myArraytoStringFunction = input => { // for (var i = 0; i < input.length; i++) { // ???? // } return input.toString(); }; // call function const anything1 = console.log(myArraytoStringFunction(myArray)); 

如果累加器不为空,则可以使用reduce ,添加一个空格:

 const myArray = ["Hey", "there"]; const myArraytoStringFunction = input => input.reduce((a, item) => ( a + (a === '' ? item : ' ' + item) ), ''); console.log(myArraytoStringFunction(myArray)); 

const myArraytoStringFunction = function myArraytoStringFunction(input) {
    let r = "";
    input.forEach(function(e) {
        r += " " + e;
    }
    return r.substr(1);
};

我假设您要避免join因为这是一项家庭作业,因此我没有使用reduce ,他们可能还没有这样做。

这是使用递归的替代方法:

 const myArray = ["Hey", "there"]; const myArraytoStringFunction = inp => (inp[0] || "") + (inp.length>1 ? " " + myArraytoStringFunction(inp.slice(1)) : ""); const anything1 = console.log(myArraytoStringFunction(myArray)); 

您可以通过使用累加器来使用reduce来检查是否将分隔符添加到字符串中。

 const array = ["Hey", "there"]; arrayToString = array => array.reduce((r, s) => r + (r && ' ') + s, ''); console.log(arrayToString(array)); 

const myArraytoStringFunction = input => {
    let product = "";
    input.forEach(str => product += " " + str);\
    // original answer above returned this:
    // return product.substr(1); 
    // I used .slice() instead
    return product.slice(1); 
};

// This was another that I like - Thank you whomever submitted this
// I did change it a little bit)
// const myArraytoStringFunction = input => {
//     let product = "";
//     input.forEach((str, i) => product += i === 0 ? str : " " + str);
//     return product;
// };


console.log(myArraytoStringFunction(["I", "think", "it", "works", "now"]));
console.log(myArraytoStringFunction(["I", "win"]));
console.log(myArraytoStringFunction(["Thank", "you"]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM