我有一个函数,当我传递数组和剩余参数时,它会返回不同的值。当我用 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']
最佳答案
在第一个示例中,您应该像这样调用该函数:
console.log(checkTerm('this', 'them', 'else'));
按照您调用它的方式,terms
是一个包含单个元素的数组,该元素为 ['this', 'them', 'else']
。
“rest”运算符旨在将单独的参数转换为数组,因此您不应将数组直接传递给它(除非您想要数组的数组...)。
关于javascript - 传递数组参数与其余参数时返回值之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58291938/