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.
It's not php - you should use
var variable_name = new Array()
or even better
var variable_name = []
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()
It's [] in ECMAScript; this isn't PHP. The interpreter is right - array is not defined, which is why you're getting that.
var articleHTML = new Array();
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
Instead of
var articleHTML = array();
and
var bodyHTML = array();
do
var articleHTML = [];
and
var bodyHTML = [];
You first need to define
var divarray = new Array();
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();)
Related
So I'm working with some slightly tricky code. Basically, I'm trying to pull a <script> tag from around 10 pages on a site I'm developing for. This code's syntax is incorrect, as you cannot use brackets in function parameters, but it's the essence of what I'm trying to perform:
var parser = new DOMParser();
var resp = new Array();
var htmlDoc = new Array();
var findScripts = new Array();
var searchScripts = new Array();
var scriptContent = new Array();
for (var i = 0; i < amt; i++) {
resp[i] = prodDetails[i].responseText;
htmlDoc[i] = parser.parseFromString(resp[i],"text/html");
findScripts[i] = htmlDoc[i].body.querySelectorAll('script');
searchScripts[i] = Array.prototype.filter.call(findScripts[i], function (findScripts[i]) {
return RegExp('var prodInfo = ').test(findScripts[i].textContent);
});
scriptContent[i] = searchScripts[i].innerText;
}
Further, possibly unneeded details:
I'm using the following code to grab each page:
var text = "";
var prodDetails = new Array();
var amt = document.querySelectorAll('[id="product-details"]').length;
for (var i = 0; i < amt; i++) {
prodDetails[i] = $.get(itemPages[i].href, {}, function (results) {
});
}
Following this, I am then parsing the information so that the tag can be pulled through simple JavaScript commands:
var parser = new DOMParser();
var resp = new Array();
var htmlDoc = new Array();
for (var i = 0; i < amt; i++) {
resp[i] = prodDetails[i].responseText;
htmlDoc[i] = parser.parseFromString(resp[i],"text/html");
}
This works for accessing each page's DOM individually by calling htmlDoc[0] through htmlDoc[9], but there are around 8 <script> tags on each of the pages. The one that I'm looking for contains specific text in its innerHTML. I can find the one I'm looking for using:
var findScripts = htmlDoc[0].body.querySelectorAll('script');
var searchScripts = Array.prototype.filter.call(findScripts, function (findScripts) {
return RegExp('var prodInfo = ').test(findScripts.textContent);
});
var scriptContent = searchScripts[0].innerText;
This code works great when ran on its own, but this means manually running each time changing the index value of htmlDoc, and I'm looking for more of an "all at once" solution.
I'm not opposed to using jQuery in this, but I am mostly unfamiliar with it. If there is a more powerful jQuery-based solution, I will take that as well. Any help is appreciated! Thank you!
Rather than assigning to someArr[i] and someOtherArr[i] over and over, I suggest just pushing to the arrays in question instead, the code will look a lot cleaner. Also, you can use forEach for better abstraction, to avoid manual iteration, and to avoid the problems with i hoisting:
const parser = new DOMParser();
const responseTexts = [];
const htmlDocs = [];
const findScripts = [];
const filteredScripts = [];
const scriptContent = [];
prodDetails.forEach((response) => {
const responseText = response.responseText;
const newDoc = parser.parseFromString(responseText,"text/html");
const thisDocScripts = newDoc.querySelectorAll('script');
const thisDocFilteredScripts = [...thisDocScripts]
.filter(oneScript => oneScript.textContent.includes('const prodInfo = '));
const thisDocScriptsContent = thisDocFilteredScripts.map(scr => scr.textContent);
responseTexts.push(responseText);
htmlDocs.push(newDoc);
findScripts.push(thisDocScripts);
filteredScripts.push(thisDocFilteredScripts);
scriptContent.push(thisDocScriptsContent);
});
Abstraction is wonderful.
Do you really need all of those variables saved in arrays, though?
I have a JavaScript code which has 4 3-dimensional arrays that are each of 500x500x220 dimension (all 220 values in the last dimension are rarely all used). Because of this large dimension, it's much faster to define one array like this and then define the four arrays from that one. The problem is that then, when I change a value in one array, it changes in the others also. Here's my code:
<script type="text/javascript">
var content = new Array();
var signs = new Array();
var sens = new Array();
var props = new Array();
var ini = new Array();
for(i = 0; i < 500; i++){
ini[i] = new Array();
for(j = 0; j < 500; j++){
ini[i][j] = new Array();
}
}
content = ini;
signs = ini;
sens = ini;
props = ini;
function f(){
alert(signs[3][3][2]); //Returns undefined
content[3][3][2] = 2;
alert(signs[3][3][2]); //Returns 2
}
f();
</script>
Notice that the f() function is only supposed to change the content array but it also changes the signs array. Why does it do that and how do I get around it?
In case it makes a difference, I'm using HTA.
With the help of this post about copying nested arrays.
Your code:
content = ini;
signs = ini;
sens = ini;
props = ini;
makes the arrays to point to ini. That's why any reference to content[0], for instance, is a reference to signs[0] and ini[0] as well.
Use:
function copy(arr){
var new_arr = arr.slice(0);
for(var i = new_arr.length; i--;)
if(new_arr[i] instanceof Array)
new_arr[i] = copy(new_arr[i]);
return new_arr;
}
to copy the arrays:
content = copy(ini);
signs = copy(ini);
sens = copy(ini);
props = copy(ini);
I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.
I have Two Arrays in Javascript as shown below :
Array one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
Array two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
Now Some how i need to loop through this Array and construct a function as shown
function NoisyData() {
return "" +
"Date,A\n" +
"20061001,3.0\n" +
"20061002,3.1\n" +
"20061003,3.2\n" +
"20061120,4.0\n" ;
}
Please help me as how to do this ??
How about this?
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push('3.0');
two.push('3.1');
two.push('3.2');
two.push('3.3');
function NoisyData() {
var result = "Date,A\n";
for(var i = 0; i < one.length;i++){
result += one[i] + "," + two[i] + "\n";
}
return result;
}
alert(NoisyData());
The faster way for long array is :
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
function NoisyData() {
var ret = [];
ret.push("Date,A");
for (var i=0;i<one.length;i++){
ret.push(one[i]+','+two[i]);
}
return ret.join('\n');
}
alert(NoisyData());
Your code can be a lot shorter. You can't type variables (like Array one) in javascript. To declare an Array most of the time an Array literal is sufficient.
If your arrays have the same length, you can use the code hereby to combine them into the string you need:
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combine = function(a1,a2){
var i = -1, len = a1.length, res = ['Date,A'];
while(++i < len){
res.push(a1[i]+','+a2[i].toPrecision(2));
}
return res.join('\n');
}(one,two);
Try it # http://jsfiddle.net/KooiInc/jdn6U/
You mean
function NoisyData() {
var txt = "Date,A\n"
for (var i=0, n=one.length;i<n;i++) {
txt += one[i]+","+two[i]+"\n"
}
return txt
}
UPDATE based on KooiInc's posts:
<script>
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combined = function(res,two){
var i = one.length;
while(i--){
res[i]+=','+two[i].toPrecision(2);
}
res.splice(0,0,'Date,A');
return res.join('\n')
}(one.slice(0),two);
alert(combined);
</script>
Instead of one.slice(0) one.clone() can be implemented as
Array.prototype.clone = function() { return this.slice(0); }
or just pass one itself instead if it is OK to modify the original array
Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values
mystring = 4|black|cat, 7|red|dog, 12|blue|fish
Here's where I want to be:
I want to end up with three arrays.
array1=("4","7","12")
array2=("black","red","blue")
array3=("cat","dog","fish")
I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.
I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:
var arr1 = [], arr2 = [], arr3 = [],
mystring = "4|black|cat, 7|red|dog, 12|blue|fish";
mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) {
arr1.push($1);
arr2.push($2);
arr3.push($3);
});
Example
You want to use the split() method :
var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]
//etc...
Like this?:
var values = mystring.split(',');
var arrays = new Array();
for(var i=0; i < values.length; i++) {
var parts = values[i].split('|');
for(var j = 0; j < parts.length;j++) {
if(!arrays[j]) {
arrays[j] = new Array();
}
arrays[j].push(parts[j]);
}
}
Will give you an array that contains those three arrays.
var str = '4|black|cat, 7|red|dog, 12|blue|fish';
var tmp = str.split(',');
var firstArray = Array();
var secondArray = Array();
var thirdArray = Array();
for( var i in tmp ){
var splitted = tmp[i].split('|');
//alert(true);
firstArray[i]=splitted[0];
secondArray[i]=splitted[1];
thirdArray[i]=splitted[2];
}