Javascript Can';join()函数参数-TypeError:undefined不是函数
最起码的例子:Javascript Can';join()函数参数-TypeError:undefined不是函数,javascript,node.js,v8,ecmascript-5,Javascript,Node.js,V8,Ecmascript 5,最起码的例子: function test() { console.log(arguments.join(',')); } test(1,2,3); 然后我得到: TypeError:undefined不是函数 但是,当我对数组执行相同操作时: console.log([1,2,3].join(',')); (function () { console.log(typeof [] == typeof arguments) })(); 我明白了 “1,2,3” 正如所料 阿鲁姆有什
function test() {
console.log(arguments.join(','));
}
test(1,2,3);
然后我得到:
TypeError:undefined不是函数
但是,当我对数组执行相同操作时:
console.log([1,2,3].join(','));
(function () {
console.log(typeof [] == typeof arguments)
})();
我明白了
“1,2,3”
正如所料
阿鲁姆有什么问题?假设它是一个数组:
console.log([1,2,3].join(','));
(function () {
console.log(typeof [] == typeof 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
不是一种类型<代码>类型[]==“对象”也可以。但是,您可以使用
Array.isArray(arguments) // false
Array.isArray([]) // true
问题在于
参数本身不是javascript数组。它在某些方面的行为类似于数组,但在其他方面则没有
为什么不尝试将其转换为纯javascript数组呢。这可以通过以下方式完成:
(function () {
var args = Array.prototype.slice.call(arguments, 0);
console.log(typeof [] === typeof args);
}());