【问题标题】:Difference between return value when passing array parameter vs rest parameter?传递数组参数与休息参数时返回值之间的区别?
【发布时间】:2020-02-06 01:41:32
【问题描述】:

我有一个函数,当我传递一个数组和一个 rest 参数时,它会返回不同的值。当我用 Array.isArray() 检查每个时,它们都是数组。为什么返回值不同?

function checkTerm(...terms) {

  var checkSet = ['that','this','else','now'];

  return terms.filter(term => checkSet.indexOf(term) > -1);
}

console.log(checkTerm(['this', 'them', 'else']));

对比

function checkTerm(terms) {

  var checkSet = ['that','this','else','now'];

  return terms.filter(term => checkSet.indexOf(term) > -1);
}

console.log(checkTerm(['this', 'them', 'else']));

作为休息传递参数:预期输出 = ['this','else'],实际输出 = []

将参数作为数组传递:预期输出 = ['this','else'],实际输出 = ['this','else']

【问题讨论】:

标签: javascript arrays


【解决方案1】:

在您的第一个示例中,您应该这样调用函数:

console.log(checkTerm('this', 'them', 'else'));

您调用它的方式,terms 是一个具有单个元素的数组,该元素是 ['this', 'them', 'else']

“rest”运算符旨在将单独的参数转换为数组,因此您不应将数组直接传递给它(除非您想要数组数组......)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 2011-12-05
    • 2013-10-21
    • 2021-12-07
    • 2014-02-06
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多