Seo Forum

Coding & Programming => JavaScript Forum => Topic started by: ngomaichi on 05-25-2016, 04:04:17

Title: Typeof array == object??
Post by: ngomaichi on 05-25-2016, 04:04:17
dev in Firefox v37.0.2 on Max OSX Yosemite

var a = new Array('first', 'second', 'third', 'fourth')
alert(typeof(a)); // => 'object' (?)

I am developing a module that needs to distinguish the input argument type.
So I am using:
Code:
//constructor function code... etc...
var arrayInput = []
var objectInput = {}
switch(typeof(arg)) // arg == ['first', 'second', 'third', 'fouth', ]
   {
    case 'array': // for example ['first', 'second', 'third', 'fouth', ]
    alert('case array')
    arrayInput = arg;
    break;
    case 'string':
    break;
    case 'object': // for example {'find':'literal', 'type':'string', 'proc':function(a){/* callback code */}}
    alert('case object')
    objectInput = arg;
    break;
   }
// ... etc ...
array literal is coming up as 'object'
So I tried the code at the top of this post: specify an array using new Array, still an object type.
What is going on here, beside maybe problems with my code I haven't noticed yet?

Edit: It appears that the only way to distinguish an array from an object in this context is to look for
the length attribute (as the texts I use tell me, everything in javascript is an object, except primitives.
Yet strings have a length attribute and have a constructor function, and behave similar to arrays in the
sense that each char has an index). I won't complain.

Thanks for time and attention
Title: Re: Typeof array == object??
Post by: ngomaichi on 05-30-2016, 21:09:23
Can you help me???
--------------
Title: Re: Typeof array == object??
Post by: raghuramastrologer on 07-16-2019, 02:00:21
The typeof an array is an object. In JavaScript, arrays are technically objects; just with special behaviours and abilities. For example, arrays have a Array.prototype.length property, which will return the number of elements in the array