简体   繁体   中英

Why returns Object.keys() an object (looks like array)?

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.

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM