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.

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah this is useful. Just wanted to have the output as array and run first time into it. ;)
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

2 Comments

OOps, as easy as this? Everything is an object in Javascript, right, hmm? OK: 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? ;)
@dollarvar Check out that last minute edit I made. Yeah, it's pretty basic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.