不能.join()函数参数 - TypeError:undefined不是函数

Jas*_*son 3 javascript v8 node.js ecmascript-5

最小例子:

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

test(1,2,3);
Run Code Online (Sandbox Code Playgroud)

然后我得到:

TypeError:undefined不是函数

但是,当我对数组执行相同操作时:

console.log([1,2,3].join(','));
Run Code Online (Sandbox Code Playgroud)

我明白了

"1,2,3"

正如所料.

这个问题有什么不对?它假设是一个数组:

(function () {
  console.log(typeof [] == typeof arguments)
})();
Run Code Online (Sandbox Code Playgroud)

真正

log*_*yth 6

参数不是数组.

(function(){
   console.log(typeof arguments);
})();
// 'object'
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

请注意,您的示例有效,因为array它不是类型.typeof [] === 'object'也.但是,您可以使用检查对象是否为数组

Array.isArray(arguments) // false
Array.isArray([]) // true
Run Code Online (Sandbox Code Playgroud)