簡體   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