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

时间:2018-07-30 19:57:23

标签: javascript arrays tostring

我正在尝试寻找.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));

5 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

我假设您正在回避join,因为这是一项家庭作业,所以我没有使用reduce,他们可能还没有这么做。

答案 2 :(得分:0)

这是使用递归的另一种选择:

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

答案 3 :(得分:0)

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

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

console.log(arrayToString(array));

答案 4 :(得分:0)

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"]));