【问题标题】:Writing a function to console.log, how can i pass multiple values? [duplicate]将函数写入console.log,如何传递多个值? [复制]
【发布时间】:2020-01-23 04:20:57
【问题描述】:

console.log每次都很难写,所以我为它创建了一个函数,

function showi(input){
 console.log(input);
 }
 
showi('hello');

但问题是,它不能传递多个参数。 例如:

function showi(input){
 console.log(input);
 }
 
let array1 = ['a', 'b', 'c'];

for(const [index, value] of array1.entries()){
 showi(index, value);
 }
 
//value will also print if I use console.log instead of `showi` function

如何在showi 函数中传递多个值?

【问题讨论】:

  • 如果可以使用 ES6,请将函数头和 console.log 调用中的 ...input 替换为 input
  • 使用function showi() { console.log(...arguments); }
  • @Chris G console.log(...arguments);工作,谢谢。

标签: javascript


【解决方案1】:

如果您发现console.log 使用起来很大,那么只需将其分配给类似logIt 的变量,如下所示。在这种情况下,您可以像使用 console.log 一样使用单个或任意数量的参数

window.logIt=console.log;
logIt('hello');
let array1 = ['a', 'b', 'c'];
logIt('array1 : ',array1);

【讨论】:

  • 哪个更好window.logIt或者做一个函数logIt(),他们有什么区别?
  • @Ankit 您可以使用window.logIt=console.loglogIt=console.log 调用logIt,并带有任意数量的参数,例如console.log
  • 为什么let print = document.write; 的工作方式不一样?
【解决方案2】:

解决方案 1 - 使用参数

function showi(){
 console.log(...arguments);
}

解决方案 2 - 使用您自己的参数名称

function showi(...textToPrint){
 console.log(...textToPrint);
}

【讨论】:

    【解决方案3】:

    使用arguments 对象

    function showi() {
        console.log(...arguments);
    }
    

    或者你也可以在 es6 中使用 rest 和 spread 运算符 -

    function showi(...args) {
        console.log(...args);
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用Array.isArray 检查输入是否为数组,并在此基础上显示内容。

      function showMe(input) {
        if (Array.isArray(input)) {
          console.log(...input);
        } else {
          console.log(input);
        }
      }
      
      showMe('sandip');
      showMe(['a', 'b', 'c'])

      同样您可以添加其他检查。

      【讨论】:

      • typeof input === 'array' javascript 中没有 array 类型
      • 我的错,修改了答案。
      • 另外,OP 想要传递多个参数,而不是数组。
      猜你喜欢
      • 2013-09-15
      • 2016-09-10
      • 2021-12-07
      • 2022-11-12
      • 1970-01-01
      • 2017-07-15
      • 2015-06-23
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多