javascript 当Javascript中的数组为空时在数组中添加元素不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18769166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:10:15  来源:igfitidea点击:

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

javascriptarrays

提问by Vignesh

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

我在 javascript 数组中遇到问题...我在 JS 中使用 Serversent 事件。我会经常从服务器获取很少的值...

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...

现在的问题是,在第一个请求期间,我将获取由逗号分隔的值.. 我在 js 中有数组对象...我将检查数组是否为空,如果是,那么我将包含组合中的值.. .

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 )

因为如果数组为空,我在数组中添加了一些值,所以我没有在 div 中打印任何值(//打印一些值),而是得到(//一些任务...打印)

回答by Andy

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>
}