javascript - Is it okay to use floating point numbers as keys in objects? -


is ok use float numbers keys in javascript objects? woudn't there potential problems such objects?

consider below code:

var obj = {}; obj[1.2345]   = 10; obj[10000]    = 10; obj[10000.23] = 10; 

is ok use float numbers keys in javascript objects?

yes, mostly. property names (keys) strings* (even ones think of array indexes, in javascript's standard arrays, because those aren't arrays). when write

obj[1.2345] = 10; 

what you're writing is:

obj[string(1.2345)] = 10; 

e.g.

obj["1.2345"] = 10; 

and it's fine have property name 1.2345 (as string) in object.

the reason said "mostly" above floating-point numbers used javascript (and other languages) aren't precise; if did this:

obj[0.3] = 10; 

and then

var key = 0.1; key += 0.2; console.log(obj[key]); // undefined 

that's undefined because 0.1 + 0.2 comes out 0.30000000000000004, rather 0.3, , object doesn't have property named 0.30000000000000004.


* "...all property names...are strings..." true through es5, of es2015 (aka es6), there's new property name type: symbol. properties have string names, use cases symbol important outnumbered "normal" property names.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -