Can't .join()函数参数- TypeError: undefined不是函数

Can't .join() function arguments - TypeError: undefined is not a function

本文关键字:函数 参数 TypeError undefined join Can      更新时间:2023-09-26

最小示例:

function test() {
  console.log(arguments.join(','));
}
test(1,2,3);

得到:

TypeError: undefined is not a function

然而,当我对数组做同样的操作时:

console.log([1,2,3].join(','));

"1、2、3"

论证有什么问题?它应该是一个数组:

(function () {
  console.log(typeof [] == typeof arguments)
})();
真正

Arguments不是数组。

(function(){
   console.log(typeof arguments);
})();
// 'object'

它是一个类似数组的结构体,具有长度和数值属性,但实际上不是数组。如果你愿意,你可以在上面使用数组函数。

function test() {
    console.log(Array.prototype.join.call(arguments, ','));
    // OR make a new array from its values.
    var args = Array.prototype.slice.call(arguments);
    console.log(args.join(','));
}
test(1,2,3);

注意,您的示例之所以有效,是因为array不是类型。typeof [] === 'object'也。但是,可以使用

来检查对象是否为数组
Array.isArray(arguments) // false
Array.isArray([]) // true

问题是arguments本身不是javascript数组。它在某些方面表现得像一个数组,但在其他方面却不是。

你为什么不把它转换成一个纯javascript数组呢?这可以通过以下方式完成:

(function () {
   var args = Array.prototype.slice.call(arguments, 0);
   console.log(typeof [] === typeof args);
}());