admin管理员组文章数量:1417421
I have a for loop that goes through a series of data. I would like to store the result of elevations[i].elevation*3.28084; in an array. Right now it only has one value outside of the loop.
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2 = elevations[i].elevation*3.28084; // convert meters to feet
}
I have a for loop that goes through a series of data. I would like to store the result of elevations[i].elevation*3.28084; in an array. Right now it only has one value outside of the loop.
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2 = elevations[i].elevation*3.28084; // convert meters to feet
}
Share
Improve this question
asked Mar 28, 2018 at 16:48
blg2blg2
38510 silver badges23 bronze badges
4 Answers
Reset to default 3You need to assign to array entries, not to the array itself:
data2[i] = elevations[i].elevation*3.28084;
// --^^^
Alternately, use push
:
data2.push(elevations[i].elevation*3.28084);
// --^^^^^^-------------------------------^
You want to push new items elevation[i].elevation * 3.28084
into array. However, it's more convenient to use Array.prototype.map:
var data2 = elevations.map(function (elevation) {
return elevation.elevation * 3.28084
})
You're only assigning a value to the previously declared variable data2
, use the function push
instead to add new values to the array, or use the current index to add new values to that array.
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2.push(elevations[i].elevation * 3.28084); // convert meters to feet
}
You have to push your result to that array like this :
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2.push(elevations[i].elevation*3.28084); // convert meters to feet
}
Or you can insert data to that array using map :
var data2 = elevations.map(function(value){
return value.elevation*3.28084;
}
本文标签: javascriptadd for loop results to an empty arrayStack Overflow
版权声明:本文标题:javascript - add for loop results to an empty array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745261861a2650391.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论