简体   繁体   中英

Arrays in javascript with jquery

I want to create an array with would hold all option element values and html text. And in a result I would like something like this:

console.log( myArray );

output:

[ "htmlText" : '0', "htmlText2" : '1', ... ]

if this is possible, how can I access them and get their keys?

or at least 2dim array

How Can I do that?

this is what I have now:

function optionValues( selectEl )
{
    var values = [];
    if ( selectEl.length )
    {
        $(selectEl).find('option').each( function(){
            values.push( $(this).val()  );
        });
        return values;
    }
    else
    return false;
}


function optionHtmls( selectEl )
{
    var html = [];
    if ( selectEl.length )
    {
        $(selectEl).find('option').each( function(){
            html.push( $(this).html()  );
        });
        return html;
    }
    else
        return false;
}

The function can be simplified:

function optionValues(selectEl) {
    var options = {};
    $(selectEl).find('option').each(function() {
        options[this.label] = this.value;
    });
    return options;
}

console.log(optionValues('select')) // {Text 1: "1", Text 2: "2", Text 3: "3"} 

Demo: http://jsfiddle.net/c5e3vemo/

Use {} instead of [] to make an associative array.

var values = {
  htmlText: 0,
  htmlText2: 1,
};

console.log(values['htmlText']);

To append things to an associative array (also referred to as an object):

values['stuff'] = 'foo';
values['thing'] = 'bar';

To loop over this:

for (var key in values) {
  /* check to make sure it's actually a valid key */
  if (values.hasOwnProperty(key)) {
    console.log(key + " => " + values[key]);
  }
}

An object would suit your needs best in this case. You can use map() to create one from the option elements in any given select . Try this:

var values = $('#mySelect option').map(function() {
    var obj = {};
    obj[$(this).text()] = $(this).val();
    return obj;
});

Example fiddle

Given this HTML:

<select id="mySelect">
    <option value="1">Foo</option>
    <option value="2">Bar</option>
</select>

The returned object would look like this:

[
    { "Foo": "1" },
    { "Bar": "2" }
]

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