[Interest] undefined as JS object key in QML?

Jason H jhihn at gmx.com
Fri Jan 3 21:09:11 CET 2020


Ah, yes, those JS quirks. Been hacking with Python, where None as a key is completely legal.
Object.keys(o).forEach((k)=>{console.log(typeof(k));}); would have told me I was in error.
Interesting confluence of things:
JS console does not print the keys as string:
>  var a = {a:1, b:2, undefined:0}
undefined
> a
{ a: 1, b: 2, undefined: 0 } <-- this messed me up!!

But it seems QML forces the keys as strings (which the console does not) 

Anyway, thanks for such a thorough explanation!


> Sent: Friday, January 03, 2020 at 12:25 PM
> From: "Jérôme Godbout" <godboutj at amotus.ca>
> To: "Jason H" <jhihn at gmx.com>, "interestqt-project.org" <interest at qt-project.org>
> Subject: RE: [Interest] undefined as JS object key in QML?
>
> The key is always a string into named array, so you undefined key is transform (optional quote there for JS which is lazy and useless rule) into "undefined" string literal.
> 
> What you want to do is a prototype or a function that will verify this for you:
> 
> function dictKey(dict, key, defaultKey = "undefined")
> {
>   if(key === undefined || !(key in dict))
>      return dict[defaultKey];
>   return dict[key];	
> }
> 
> That would do it in a better way, you can also make it a prototype if you want, make it easier to use most of the time.
> dictKey(textForColor, color) should now return the proper value and the binding should still work.
> 
> -----Original Message-----
> From: Interest <interest-bounces at qt-project.org> On Behalf Of Jason H
> Sent: January 3, 2020 11:46 AM
> To: interestqt-project.org <interest at qt-project.org>
> Subject: [Interest] undefined as JS object key in QML?
> 
> Simplified example:
> Text {
>     property var textForColor: {"transparent": "Waiting", "lime": "Ready", undefined: "Initializing"}
>     text: textForColor[color]
>     color: // set somewhere else, potentially undefined at the start }
> 
> But if I include the undefined key, QML complains.
> Fails execution with: Expected token `}'
> If the undefined key-pair is first, then QtCreator complains that the colon after "transparent" as:
>   Expected token `,'
> If the undefined key-pair is last, then QtCreator complains that the colon after "transparent" as:
>   Invalid property name "text"
> 
> 
> However in Node it works just fine (JS REPL):
> > var a = {undefined: "!", "1":"B"};
> undefined
> > a
> { '1': 'B', undefined: '!' }
> > a[undefined]
> '!'
> > Object.keys(a)
> [ '1', 'undefined' ]
> 
> Bug?
> Sure there are ways to work around this (change undefined to be a string, and when indexing color, make that a string too) but shouldn't this be able to support it as undefined itself?
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest
>


More information about the Interest mailing list