【问题标题】:Shortcut of calling a method without writing parameters in JavascriptJavascript中不写参数调用方法的快捷方式
【发布时间】:2020-10-14 00:47:16
【问题描述】:

以下是我需要澄清的代码。我希望这段代码能像 Option 2 一样逐个控制台 'mango', 'apple', 'orange' 但这会引发另一个输入,我不知道 JavaScript 是如何吐出这个输出的。

const myFunc = (...data) => (data.map(console.log))

myFunc('mango', 'apple', 'orange')

选项 2 -(预期输出)

var myFunc = (...data) => {
  data.map(x => {
    console.log(x)
  })
}

myFunc('mango', 'apple', 'orange')

请更正我的理解,因为我认为data.map(console.log) 只会记录这些项目。

【问题讨论】:

标签: javascript html reactjs loops ecmascript-6


【解决方案1】:

您的代码运行良好,应该会为其他函数产生预期的结果。

Array#map 接受一个回调函数,它将为数组的每个元素调用该函数。 MDN:

回调函数接受以下参数:

currentValue
数组中正在处理的当前元素。

indexOptional
当前正在处理的元素在数组中的索引。

arrayOptional
调用了数组映射。

因为您将 console.log 作为回调函数传递,所以您实际上是在编写以下代码:

const myFunc = (...data) => (data.map((curVal,index,arr) => console.log(curVal,index,arr)))

myFunc('mango', 'apple', 'orange')

所以额外的输出是因为您也在不知不觉中记录了indexarray 参数。

请注意,您使用的任何其他函数也将接收这些额外参数。如果他们只接受一个参数,那么它应该完全按照您的预期工作。

【讨论】:

    【解决方案2】:

    console.log 接受多个参数。

    您可以将您的函数包装在另一个函数中并仅使用第一个参数。

    如果map的结果从不使用,forEach会更好。

    const single = fn => first => fn(first);
    
    var myFunc = (...data) => {
        data.forEach(single(console.log));
    }
    
    myFunc('mango', 'apple', 'orange')

    【讨论】:

    • 非常感谢分享最佳做法 :) +1
    • 快速查询,是否建议使用扩展运算符来接受多个参数,或者我们应该避免这种方法?
    • @Nesh,这取决于...对不起。
    • @Nesh,当在参数列表中使用时,它是rest parameter。这是一种语言功能,如果您的目标是接受完全任意数量的参数,则绝对应该使用它。如果您知道参数的数量,则应明确指定它们。
    【解决方案3】:

    这是 map 在后台所做的:

    function map(a, f) {
      var b = new Array(a.length);
      for (let i = 0; i < a.length; i++) {
        b[i] = f(a[i], i, a);
      }
      return b;
    }
    
    console.log(
      map([0, 1, 2, 3], function(x, i, a) {
        return x * x;
      })
    );

    如您所见,f 接收 3 个参数:元素a[i],其位置i,以及数组a。是否使用它们取决于您,如这些扭曲的示例所示:

    console.log(
      ["a", "b", "c", "d"].map(function(x, i, a) {
        return x + " " + a[(i + 1) % a.length];
      })
    );
    
    console.log(
      ["a", "b", "c", "d"].map(function(_, i) {
        return "2^" + i + " = " + 2 ** i;
      })
    );

    由于console.log 接受任意数量的参数,如果您将其直接传递给map,它将使用所有三个参数a[i]ia。要仅选择一个参数,您需要一个过滤器:

    "abcd".split("").map(function(x) {
      console.log(x);
    });

    但是,正如 Nina 所说,forEach 在这种情况下更合适,因为我们忽略了map(即[undefined × 4])的输出:

    "abcd".split("").forEach(function(x) {
      console.log(x);
    });

    【讨论】:

      【解决方案4】:

      选项 1 中的输出将是:-

      mango 0 (3) ["mango", "apple", "orange"]
      apple 1 (3) ["mango", "apple", "orange"]
      orange 2 (3) ["mango", "apple", "orange"]
      

      这是因为以下两个原因:-

      ma​​p() 方法使用为每个数组元素调用函数的结果创建一个新数组。 ma​​p() 方法按顺序为数组中的每个元素调用提供的函数一次。

      【讨论】:

        猜你喜欢
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多