0

I have come across this:

var stdin = {123:1,423:1};

var stdout = Object.keys(stdin);

console.log(stdout);             //["123", "423"] 
console.log(typeof(stdout));     //object
console.log(stdout[0])           //123

ECMAScript® Language Specification says:

15.2.3.14 Object.keys ( O )

When the keys function is called with argument O, the following steps are taken:

... 6. Return array.

JSFIDDLE: http://jsfiddle.net/wpVvv/1/

Tested on Chrome and Firefox on Windows 7.

What is going on? Should be array, looks like array to me, is Object?

Edit:
typeof(). Arrgh.

Community
  • 1
  • 1
loveNoHate
  • 1,549
  • 13
  • 21

2 Answers2

1

Why are you saying it's an object? Running typeof on an Array will always return 'object'.

var arr = [1,2,3];
typeof arr --> "object"

Try instead

Array.isArray(arr) --> true

Here's the test you wanted.

var stdin = {123:1,423:1};
Array.isArray(stdin) --> false
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • 1
    OOps, as easy as this? Everything is an object in Javascript, right, hmm? OK: http://ecma-international.org/ecma-262/5.1/#sec-11.4.3. Arrgh. ;) Think this question should run: How does `typeof()` work? Can I delete it please? ;) – loveNoHate Feb 08 '14 at 06:23
  • @dollarvar Check out that last minute edit I made. Yeah, it's pretty basic. – Tyler McGinnis Feb 08 '14 at 06:24
1

Arrays are objects.

Try typing typeof([1,2,3]) into your console - you'll also get object as the result.

Now, if you type Object.prototype.toString.call( [1,2,3] ), you'll get [object Array], which is somewhat useful (and you'll get the same result for the return value of Object.keys).

If you want a boolean result, just use Array.isArray (see this related answer)

Community
  • 1
  • 1
Krease
  • 15,805
  • 8
  • 54
  • 86