Declare an empty array in javascript

update

My code that works. When the page is loaded

product= [[],[]]; 

then the code executed after ajax call:

 $('#contextreload ul').each(function(i, ul) { product.push([]); }); $('#contextreload ul').each(function(i, ul) { allline=i; $('#reloadajax'+i+' li').each(function(lk, li) { var lilk = $(li).html(); product[i][lk]=lilk; // your code goes here }); // your code goes here }); 

Use eval (); in ajax answer for this, with some changes in php file? / EndUpdate

product [0] = [1,2,3,4];

product [1] = [a, b, x, g];

.

.

product [10] = [extra, extra, extra, extra];

When I load a page, this is done: product= [[],[],[],[],[],[],[],[],[],[]];

But if I declare this when I call ajax, I can push add data only to this array (10 rows) If I have 11 rows ( product[10][0] and product[10][1] ), extra data will not be added. After calling ajax, I need additional data: product= [[],[],[],[],[],[],[],[],[],[],**[11]**];

This function is related to the fact that I want to put data into an array after loading ajax data from a php file.

 $('#contextreload ul').each(function(i, ul) { <strike> var product = $(ul).html(); </strike> allline = i; $('#reloadajax'+i+' li').each(function(lk, li) { var lilk = $(li).html(); product[i][lk]=lilk; alert(lilk+lk); // your code goes here }); // your code goes here }); } 
+5
source share
3 answers

As a result of your ajax call, use the push() function

 product.push([]); 

This adds an array to the last product index. This creates index 10 and you have additional data.

If you want to add a dynamic row count, use this code:

 var number_of_new_row = 11; // 11 for example, you can use any number >= 0 for(; number_of_new_row--;) product.push([]); 

Another way

In your ajax return, save the new length of the product array in a global variable. And use it before your loop to reset your array and initialize it with a new length.

 var lengthArray = 10; // update the value in the callback of your ajax call 

And your loop:

 var product = []; for(; lengthArray--;) product.push([]); $('#contextreload ul').each(function(i, ul) { //<strike> var product = $(ul).html(); </strike> allline = i; $('#reloadajax'+i+' li').each(function(lk, li) { var lilk = $(li).html(); product[i][lk]=lilk; alert(lilk+lk); // your code goes here }); // your code goes here }); 
+5
source

Note: this line of your code creates a line, not an array.

 var product = $(ul).html(); //returns string not an array 

what you need is something like

 var product_arr = {}; // an object or var product_arr = []; // an array 
+2
source

The following code used to declare an empty array in javascript

 var product_arr = new Array(); //declaring empty array console.log(product_arr); 
+1
source

Source: https://habr.com/ru/post/1216076/


All Articles