I have a JSON string containing 4 objects, and each contains an Array tennisballs where this.tennisballs.length is about 2000. In my code, I thought I should get an array of 4 averages of all tennisballs' weights, but apparently I get an array of 2000 in length. Why is that?
$.each(data, function () {
var average = Array();
var sum = 0;
for (var i = 0; i < this.tennisballs.length; ++i) {
sum += parseFloat(this.tennisballs[i][2]);
if (i == (this.tennisballs.length - 1)) {
average[i] = sum / this.tennisballs.length;
average.push(average[i]);
console.log("sum: " + sum + ", average[" + i + "]" + average[i]);
}
}
console.log("average array:" + average);
});
2 Answers 2
When you assign an item at a specific index of an array and that index is outside of the length of the array, the length is adjusted after that index.
When you assign the average to average[i] and i is around 2000, it will make the array have a length of around 2000 although most items in the array are undefined.
To just put the average last in the array, don't assign it at index i, just push it. Use average.length-1 to get the index of the last item in the array. Also, you should create the array outside the loop, and display it after the loop:
var average = Array();
$.each(data, function() {
var sum = 0;
for(var i = 0; i < this.tennisballs.length; ++i){
sum += parseFloat(this.tennisballs[i][2]);
if(i == (this.tennisballs.length - 1) ) {
average.push(sum / this.tennisballs.length);
console.log("sum: " + sum + ", average["+(average.length-1)+"]: " + average[average.length-1]);
}
}
});
console.log("average array:" + average);
Side note: You can just push the avarage after the loop, instead of checking the index for each iteration in the loop:
var average = Array();
$.each(data, function() {
var sum = 0;
for(var i = 0; i < this.tennisballs.length; ++i){
sum += parseFloat(this.tennisballs[i][2]);
}
average.push(sum / this.tennisballs.length);
console.log("sum: " + sum + ", average["+(average.length-1)+"]: " + average[average.length-1]);
});
console.log("average array:" + average);
Comments
You are storing an item in the 2000th position of the average Array so it's length would always be 2000.
E.g:
> a = Array()
[]
> a[2000 - 1] = 2000/10
200
> a.length
2000
The remaining items in the Array average would be undefined in exception of the last item
forloop, and then performing the division and appending to the Array immediately after the loop. Furthermore, you might findconsole.logmore helpful if you pass multiple arguments instead of relying on an implicit cast to string, i.e.console.log("average array", average);. Finally, usingArray()is not the preferred way to create an Array (unless you want a specific constructor features), use an Array literal[].array(), you are saying instead of using average = [] makes the code more efficient? That's really interesting, I will have to read more about that.