0
var _={};

_.bullets='1,2,3';

console.log(typeof bullets);

string

console.log(_.bullets);

var bullets=_.bullets.split(',');

console.log(bullets);    //REF 1

["1", "2", "3"]

console.log(typeof bullets);

object

Why is it not array? I can't figure out what I am doing wrong here

UPDATE

console.log([1,2,3]);
console.log(bullets);    //REF 1

[1, 2, 3]

["1", "2", "3"]

What is the difference (one is a string one is a number?)

Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66
  • http://stackoverflow.com/questions/4775722/check-if-object-is-array – Andreas Jan 22 '14 at 15:03
  • 1
    The difference between [1,2,3] and ["1", "2", "3"] is that one is an array with 3 numbers, and one is an array with three strings. – JLRishe Jan 22 '14 at 15:08
  • 2
    `typeof [] === "object"` - the only objects where typeof does not yield `"object"` are functions. – Bergi Jan 22 '14 at 15:09

4 Answers4

3

typeof never returns 'array'. For instances of Array, it returns 'object':

Table 20 — typeof Operator Results

  • Undefined : "undefined"
  • Null : "object"
  • Boolean : "boolean"
  • Number : "number"
  • String : "string"
  • Object (native and does not implement [[Call]]) : "object"
  • Object (native or host and does implement [[Call]]) : "function"
  • Object (host and does not implement [[Call]]) : Implementation-defined except may not be "undefined", "boolean", "number", or "string".

Source: ECMAScript spec

Tibos
  • 27,507
  • 4
  • 50
  • 64
2

Use Array.isArray(a) or a instanceof Array.

Arrays are objects, so typeof returns object.

wprl
  • 24,489
  • 11
  • 55
  • 70
1

Technically typeof fits for primitive types while instanceof fits for reference types.

If you use typeof for some reference types (Array, Object), it will return "object". Function is the third reference type; it behaves differently (typeof wise) as it will return "function" when typeof new Function().

Based on your example you can deduce that string is a primitive type in JavaScript as typeof "blabla" === string (which returns true). Yes that's something curious if you come from a traditional strongly typed language such as Java or C#.

roland
  • 7,695
  • 6
  • 46
  • 61
0

typeof returns 'object' when supplied array values. To test for an array you can do something like this (from JavaScript the Good Parts):

var is_array = function (value) {
     return value &&
     typeof value === 'object' &&
     typeof value.length === 'number' &&
     typeof value.splice === 'function' &&
     !(value.propertyIsEnumerable('length'));
};
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
JeremyFromEarth
  • 14,344
  • 4
  • 33
  • 47