What is the official ordering standard of Object.keys()
?
This is not a question over the ordering. It is a question over standard.
Kaushal Regmi
wrote:
First, the keys that are integer indices in ascending numeric order. Then, all other string keys, in the order in which they were added to the object. Lastly, all symbol keys, in the order in which they were added to the object. https://stackoverflow.com/a/57929312/10617101
So far so good. Have a Object only integers as keys, there will be saved in ascending numeric order in the Object.keys()
returned array. Are the keys only letters, the Object.keys()
returned array have the same ordering as in the the called object{}
. My question is: Is this a general and global standard in JavaScript? The question about this is: Is it safety?
Next, there is a little problem with that. (i do not use it).
var object = { 3a: 'z', 1a: 'x', 2a: 'y' };
for (var i = 0; i < Object.keys(object).length; i++) {
console.log(Object.keys(object)[i]);
}
// Firefox: SyntaxError: identifier starts immediately after numeric literal
// Chrome: Uncaught SyntaxError: Invalid or unexpected token
var object = { a3: 'z', a1: 'x', a2: 'y' };
for (var i = 0; i < Object.keys(object).length; i++) {
console.log(Object.keys(object)[i]);
}
// works on both: [a3, a1, a2]
Yes, the solution is, use another method to create the object{}
:
var object = {};
object["3a"] = 'z';
object["1a"] = 'x';
object["2a"] = 'y';
for (var i = 0; i < Object.keys(object).length; i++) {
console.log(Object.keys(object)[i]);
}
// [3a, 1a, 2a]
EDIT: The special problem are object keys as integers in quotes:
var object = { "3": "z", "1": "x", "2": "y" };
for (var i = 0; i < Object.keys(object).length; i++) {
console.log(Object.keys(object)[i]);
} // [1, 2, 3]
Normaly "1" is a string and 1 is a integer, but as object key "1" is still a integer. (but not realy by math with object keys).
Also by the way therefore my question, what is the official standard in the order. And how safety is this.