简体   繁体   中英

assign object as key value in javascript

I am tyring to do something like this:

this.slides = {$('#Page_1') : null,
               $('#Page_2') : null,
               $('#Page_3') : null};

Why am I doing this, or what advantage do I gain?
I dont want to use jquery selectors throughout class.


A Solution:

this.slides = [{"key": $('#Page_1'), "value": null},
               {"key": $('#Page_2'), "value": null},
               {"key": $('#Page_3'), "value": null}];

Limitation:

The problem with this approach is that you have to iterate through the whole object each time you want to approach this. You should use the id as identifier, this is much more efficient. – Christoph

No, keys must be literals. you could use a property of your object.

If your processing is based on the this.slides content, why not use the id as key ? since they are also meant to be "unique" otherwise you would break the DOM. So i would suggest something like

this.slides = {'#Page_1':null,'#Page_2':null,'#Page_3':null};

And a very light modification of your processing of this.slides

Why don't you try a structure like this:

this.slides = [{"key": $('#Page_1'), "value": null},
               etc.];

Or does that break your need for using an object?

Of course, when iterating it, you'd have to use logic like:

for (var i = 0; i < this.slides.length; i++) {
    var key = this.slides[i].key;
    var value = this.slides[i].value;
}

You cannot use objects as keys, only plain literals. I'd suggest a structure like this:

this.slides = { 'Page_1' : $('#Page_1'),
                'Page_2' : $('#Page_2')
                'Page_3' : $('#Page_3')};

This way you can use the id of the elements to easily access the according jQuery-Object. (You can omit the quotes for the keys.)

slides.Page_1
// or
slides['Page_1']

now gives you the according jQuery 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