最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - add for loop results to an empty array - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 3

You 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;
}
发布评论

评论列表(0)

  1. 暂无评论