【问题标题】:Is there anyway to console.log without a newline?无论如何 console.log 没有换行符?
【发布时间】:2020-07-04 03:22:34
【问题描述】:

我想console.log() 我的数组像这样不带换行符

let myarr = [1,2,3,4,5];
myarr.forEach(e => console.log(e));

【问题讨论】:

标签: javascript console.log


【解决方案1】:

您可以改用.reduce()

let myarr = [1,2,3,4,5];
const result = myarr.reduce((a, c) => `${a}${c}`, '');
console.log(result);

我希望这会有所帮助!

【讨论】:

    【解决方案2】:

    你可以展开数组。然后将所有值作为参数。

    let array = [1, 2, 3, 4, 5];
    
    console.log(...array);

    【讨论】:

    【解决方案3】:

    为什么要为数组中的每个元素创建一个单独的 console.log?你可以这样做:

    console.log(myarr);
    

    或者,如果您的数组中有对象并且您希望看到它们全部展开,您可以这样做:

    console.log(JSON.stringify(myarr));
    

    【讨论】:

      【解决方案4】:

      您必须对输出进行字符串化。

      所以要么使用JSON.stringify(myarr)

      let string = '';
      for(let i = 1; i < 6; i += 1) {
        string += i + ' ';
      }
      console.log(string);
      

      编辑:顺便说一句,我建议在使用 javascript 时使用 camelCase。它已成为定义变量和方法时的标准。

      见:https://techterms.com/definition/camelcase

      【讨论】:

        猜你喜欢
        • 2022-08-24
        • 2011-02-03
        • 2021-01-31
        • 2013-04-08
        • 2013-03-13
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        相关资源
        最近更新 更多