Cannot use .join () function arguments - TypeError: undefined is not a function

Minimal example:

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

test(1,2,3);

      

Then I get:

TypeError: undefined is not a function

However, when I do the same for an array:

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

      

I get

"1,2,3"

As expected.

What's wrong with the reputation? Let's assume it's an array:

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

      

True

+3


source to share


2 answers


The arguments are not an array.

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

      

It's a massive structure with long and numeric properties, but it's not really an array. If you want, you can use an array function on it though.



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);

      

Note, your example works because it is array

not a type. typeof [] === 'object'

... However, you can check if an object is an array with

Array.isArray(arguments) // false
Array.isArray([]) // true

      

+6


source


The problem is that it is arguments

NOT a javascript array per se. It behaves like an array in some ways, but not in others.

Why don't you try converting it to a pure javascript array. This can be done as follows:



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

      

0


source







All Articles