I'm trying to add 2 values to an array that I extract from a html page. However, the value for key [0] always returns undefined whereas I expect 4 in this case.
<script type="text/javascript">
$(document).ready(function ()
{
var arrayList = $("some class");
var x = new Array();
var j = 0;
var k = 1;
$.each(arrayList, function(i,e) {
var MyIf = $(e).text();
x[j] = new Array();
if(k == 2) {
x[j][0] = 4; // This always returns undefined, no matter which value I assign.
}
if(k == 3) {
x[j][1] = parseInt(MyIf);
}
if(k % 3 == 0) {
j++;
k = 1;
} else {
k++;
}
});
console.log(x); // the console returns for all [0] "undefined"
});
</script>
What am I missing?
asked Apr 23, 2014 at 9:42
Kris Van den Bergh
1,1524 gold badges18 silver badges32 bronze badges
2 Answers 2
It's because you create a new array every time in your each.
x[j] = new Array();
so it's always undefined.
put it in here:
if(k % 3 == 0) {
j++;
k = 1;
x[j] = new Array();
}
and don't forget to call x[j] = new Array(); before your first run.
answered Apr 23, 2014 at 9:53
Homungus
1,1141 gold badge10 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Kris Van den Bergh
so how does it explain that the Array still has values for x[j][1] ?
Homungus
because you make a new array an then set the value
x[j][1] = somevalue;Daniël Knippers
@KrisVandenBergh Because when
k == 3 it adds to the last created Array at index 1. Then, j is increased so it will not touch that same Array anymore.Daniël Knippers
@Homungus If you do
x[j] = [] in the k % 3 == 0 case, x[j] will be undefined in the k == 2 and k == 3 cases above it the very first run. Perhaps not pretty, but you can do on the first line of the .each loop a if(typeof x[j] === 'undefined') x[j] = []; which fixes it (and remove it from the k % 3 == 0 case entirely).Homungus
@DaniëlKnippers you are right, of course it should be initialized before first run. updated answer.
|
It should be done like this:
var arrayList = [1,2,3,4,5];
var x = new Array();
var j = 0;
var k = 1;
x[j] = new Array();
$.each(arrayList, function(i,e) {
var MyIf = $(e).text();
if(k == 2) {
x[j][0] = 4; // This always returns undefined, no matter which value I assign.
}
if(k == 3) {
x[j][1] = parseInt(MyIf);
}
if(k % 3 == 0) {
j++;
x[j] = new Array();
k = 1;
} else {
k++;
}
});
console.log(x);
In your code, when the k variable is equal 3, you overwrite the previous value doing this:
x[j] = new Array();
if(k == 2) {
x[j][0] = 4; // This always returns undefined, no matter which value I assign.
}
Comments
lang-js
arrayListhave? If it has only 1, I would expectxto be empty since you only add to it whenk == 2ork == 3. In other words, how many times does your$.eachloop run?