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);
});
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.