Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding element in array when array is empty in Javascript is not working

I am facing a problem in javascript array...i am using Serversent event in JS. I will be getting few values from server frequently...

My task is to catch all the details and display in drop-down box...

Now the problem is, during the first request, i will getting values seperated by comma.. I have array object in js...i will check if the array is empty, if so, then i will include the values in combo...

code:

var varArr = new Array();


//since i am using SSE, i will executing this below part multiple times automaticall when ever server pushes data..

if(!varArr.length){
varArr[0]='somevalue';
//Printing some value in <div>
}
else{
//some task...to print in <div>
}

Since i have added some values in array if the array is empty, i am not getting any values printed in div (//Printing some value in ), instead i am getting (//some task...to print in )

like image 555
Vignesh Avatar asked Sep 12 '13 16:09

Vignesh


People also ask

How do you add an element to an empty array?

Answer: Use the array_push() Function You can simply use the array_push() function to add new elements or values to an empty PHP array.

How check array is empty or not in JavaScript?

We can also explicitly check if the array is empty or not. if (arr. length === 0) { console. log("Array is empty!") }

How do you add values to an existing array?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.


1 Answers

Perhaps you mean to do this?

var varArr = new Array();
if (varArr.length === 0) {
  varArr.push(somevalue);
  // Printing some value in <div>
} else {
  // Some task...to print in <div>
}
like image 162
Andy Avatar answered Sep 23 '22 01:09

Andy