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);
});
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);
You are storing an item in the 2000th position of the average
Array so it's length would always be 2000.
Eg:
> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.