Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill the array in jquery

Tags:

arrays

jquery

Is there any other better way to fill up the array like :

var arr = [];
var i = 0;
$('select').children('option').each( function() {
    arr[i++] = $(this).html();
});
like image 478
King Kong Avatar asked Jun 20 '12 12:06

King Kong


People also ask

How do you fill data in an array?

The fill() method fills specified elements in an array with a value. The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.

How do you fill an empty array?

Array.fill Using the Array. fill method is an obvious choice — you supply the method with the value you want to populate your array with, and the method returns a modified version of the array.

What is array fill () in JavaScript?

Array.prototype.fill() The fill() method changes all elements in an array to a static value, from a start index (default 0 ) to an end index (default array.length ). It returns the modified array.


2 Answers

You can use map method:

var arr = $("select > option").map(function() {
    return this.innerHTML;
}).get();

DEMO: http://jsfiddle.net/UZzd5/

like image 168
VisioN Avatar answered Sep 30 '22 12:09

VisioN


using push() :

var arr = [];
$('select').children('option').each( function() {
   arr.push($(this).html());
});
like image 35
mgraph Avatar answered Sep 30 '22 12:09

mgraph