10

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.

Arlen Beiler
  • 15,336
  • 34
  • 92
  • 135

8 Answers8

25

It's not php - you should use

var variable_name = new Array()

or even better

var variable_name = []
Andris
  • 27,649
  • 4
  • 34
  • 38
8

That's not how to declare variables as an empty array. You should be using:

var articleHTML = [];

See this previous question for reasoning of using this method instead of new Array()

Community
  • 1
  • 1
Chad Birch
  • 73,098
  • 23
  • 151
  • 149
2

Note! Javascript IS case sensitive you have to use upper-case A in word Array.

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
jave.web
  • 13,880
  • 12
  • 91
  • 125
2

It's [] in ECMAScript; this isn't PHP. The interpreter is right - array is not defined, which is why you're getting that.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
2
var articleHTML = new Array();
Wh1T3h4Ck5
  • 8,399
  • 9
  • 59
  • 79
derek
  • 4,826
  • 1
  • 23
  • 26
1

Instead of

var articleHTML = array();

and

var bodyHTML = array();

do

var articleHTML = [];

and

var bodyHTML = [];
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
1

You first need to define

var divarray = new Array(); 
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
Pinu
  • 7,310
  • 16
  • 53
  • 77
0

You also don't need to use var six times, you can do:

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.

Also there are a number of compelling reasons not to use new in instantiate an array (besides []; is much shorter than new Array();)