在不同系统上的Javascript中初始化的数组的初始值是多少?

What is the initial value of an initialized Array in Javascript on different systems?

本文关键字:多少 数组 系统 Javascript 初始化      更新时间:2023-09-26

几个月来我一直在为JavaScript问题而苦苦挣扎,我有一个包含一些属性的数组,后来检查其中一些属性以决定是否向用户显示消息。

现在,这一切在大多数系统(尤其是最近的浏览器)上都运行良好,但在我客户的某些IE7计算机上却不那么顺利。

现在我刚刚发现在我的代码中的某个地方,我初始化了一个如下所示的新数组,但从未真正设置"done"的值

var qar=new Array('question_no','pos','done');
qar['question_no'] = 1234;
qar['pos'] = 1234; //dont mind these numbers

稍后在一些 for 循环中,我检查:

//check if this question was already shown
if(qar['done'])
   continue; //stop here, don't show message
//set done to true, so that this question will not be shown again
qar['done'] = true;
window.alert('messaged!');

同样,出错的是有时(实际上经常,但并非总是)消息在IE7中根本不显示。

现在回答我的问题:我知道 qar['done'] 应该在初始化后立即未定义,这使我的代码工作正常(在 Chrome 等中),但是是否可以以某种方式在 IE7 中处理这种情况?例如,qar['done'] 不是未定义的,而是某个随机值,因此有时偶然被认为是真的?还是这样想着是一件愚蠢的事情?

如果这不是问题,那么我不知道是什么..

提前感谢!

通过这样做:

var qar=new Array('question_no','pos','done');

您只是在创建带有索引的数组。

qar[0] will be 'question_no'
qar[1] will be 'pos'
qar[2] will be 'done'

在这种情况下,QAS['done'] 将始终是未定义的。

这就是为什么它会引起问题。你应该使用javascript对象而不是使用数组。

但是你可以做这样的事情:

if(typeof qar['done'] === 'undefined'){
   qar['done'] = true;
   alert('messaged!');
}

你的代码应该是这样的:

var qar={};
qar['question_no'] = 1234;
qar['pos'] = 1234; //dont mind these numbers
//check if this question was already shown
if(!qar['done']) {
   //set done to true, so that this question will not be shown again
   qar['done'] = true;
   window.alert('messaged!');
}