Javascript 这个javascript有什么问题?未定义数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2860243/
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
What's wrong with this javascript? Array not defined
提问by Arlen Beiler
What's wrong with this code?
这段代码有什么问题?
var divarray = document.getElementById("yui-main").getElementsByTagName("div");
var articleHTML = array();
var absHTML;
var keyHTML;
var bodyHTML = array();
var i = 0;
for ( var j in divarray) {
if(divarray[i].className == "articleBody"){
alert("found");
articleHTML = divarray[i];
break;
}
bodyHTML[i] = '';
if(articleHTML[i].className == "issueMiniFeature"){continue;}
if(articleHTML[i].className == "abstract"){absHTML = articleHTML[i]; continue;}
if(articleHTML[i].className == "journalKeywords"){keyHTML = articleHTML[i]; continue;}
bodyHTML[i] = articleHTML[i];
i++;
}
This is the error I am getting:
这是我得到的错误:
ReferenceError: array is not defined
I am using Google Chrome if it helps any.
如果有帮助,我正在使用谷歌浏览器。
回答by Andris
It's not php - you should use
这不是 php - 你应该使用
var variable_name = new Array()
or even better
甚至更好
var variable_name = []
回答by Chad Birch
That's not how to declare variables as an empty array. You should be using:
这不是如何将变量声明为空数组。你应该使用:
var articleHTML = [];
See this previous questionfor reasoning of using this method instead of new Array()
回答by meder omuraliev
It's []in ECMAScript; this isn't PHP. The interpreter is right - arrayis notdefined, which is why you're getting that.
它[]在 ECMAScript 中;这不是 PHP。解释器是对的 -array没有定义,这就是你得到它的原因。
回答by derek
var articleHTML = new Array();
回答by RedFilter
Instead of
代替
var articleHTML = array();
and
和
var bodyHTML = array();
do
做
var articleHTML = [];
and
和
var bodyHTML = [];
回答by Pinu
You first need to define
你首先需要定义
var divarray = new Array();
回答by jave.web
Note! Javascript IS case sensitive you have to use upper-case A in word Array.
笔记!Javascript 区分大小写,您必须在单词数组中使用大写 A。
var myarr = new array(); //THIS IS WRONG! and will result in error not defined
So these are the correct ways:
所以这些是正确的方法:
var myarr = new Array(); //THIS IS CORRECT (note the "big" A) :)
var myarr = []; //and this is correct too
回答by IndieInvader
You also don't need to use var six times, you can do:
你也不需要使用 var 六次,你可以这样做:
var divarray = document.getElementById("yui-main").getElementsByTagName("div"),
articleHTML = [],
absHTML = [],
keyHTML = [],
bodyHTML = [],
i = 0;
Which works just as well as your six vars but looks much nicer.
这与您的六个 var 一样有效,但看起来更好。
Also there are a number of compelling reasons not to use new in instantiate an array (besides []; is much shorter than new Array();)
还有很多令人信服的理由不使用 new 来实例化一个数组(除了 []; 比 new Array(); 短得多)

