简体   繁体   中英

Why can't I call .join() on the result of .keys()?

I made this JS code in an HTML file:

<script>
x=[];
x["abc"]={
    a:1,
    b:2
}
x["def"]={
    a:234,
    b:5655
}

keyArrayX=x.keys();
console.log(keyArrayX.join());
</script>

When I render the file, I get this error:

Uncaught TypeError: keyArrayX.join is not a function

But the result of keys() is an array, so I don't understand what's wrong here. My goal is to return a concatenated string of all the keys in the array, in this case it would be:

abc,def

Please use Object.keys() instead of x.keys() ;

Also var x = {} is correct for dictionary

 let x = {}; x["abc"] = { a: 1, b: 2 } x["def"] = { a: 234, b: 5655 } let keyArrayX = Object.keys(x); console.log(keyArrayX.join());

"But the result of keys() is an array" ,

The return value of keys() is not array. According to MDN

Return value

A new Array iterator object.

If you want keys then use Object.keys()

 let x=[]; x["abc"]={ a:1, b:2 } x["def"]={ a:234, b:5655 } keyArrayX=Object.keys(x); console.log(keyArrayX.join());

You have to use Object.keys(x) .

 x=[]; x["abc"]={ a:1, b:2 } x["def"]={ a:234, b:5655 } keyArrayX=Object.keys(x); console.log(keyArrayX.join());

Are you sure you want to set keys in array rather than object?

x={}
x.abc = {};// will be the ideal way
x.def= {};

and then to get keys Object.keys(x) should be the way to go to have a map of keys

It should log ["abc", "def"] .

Object.keys shall work on x irrespective of it's assignment as an array or an object.

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