最小示例:
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)
})();
true
最佳答案
参数不是数组。
(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
关于javascript - 不能 .join() 函数参数 - TypeError : undefined is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25416554/