在.map中添加条件

时间:2019-06-30 19:35:29

标签: javascript

这是我要根据其权重从 list 随机选择一个城市,然后根据城市之间的距离修改权重的代码(距离越远,选择城市越多,权重越大) )。之后,我再次使用修改后的列表来随机选择其他城市。 该代码工作正常,除了一件事...

代码如下:

var list = liste.map(c => {
  var newWeight = Math.abs(baseDistance - c.distance);
  return {
    name: c.name,
    distance: c.distance,
    weight: newWeight
  };

});

在这里我创建保存修改过的liste的列表数组。

if(newWeight !== 0){
var newWeight = Math.abs(baseDistance - c.distance) + c.weight;
}

我想要的是将每个对象的 weight 添加到 newWeight 中,如下所示:

{{1}}

但是每次我得到错误。

1 个答案:

答案 0 :(得分:2)

在newWeights方法中,您为列表重新分配了一个新值...

看看这个:https://jsfiddle.net/gbc9w06y/

// list of cities
var liste = [
   { name: "New York", distance: 8, weight: 1 },
   { name: "Atlanta", distance: 4, weight: 1 },
   { name: "Dallas", distance: 2, weight: 1 },
   { name: "Los Angeles", distance: 1, weight: 1 },
];

var repeatTimes = 4;
var choose = [];
choose = [liste.map(x=>x.name), liste.map(x=>x.distance), liste.map(x=>x.weight)];

// randomaly pick a city based on its weight
var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};

var getRandomItem = function(choose, weight) {

    var total_weight = weight.reduce(function (prev, cur, i, arr) {
        return prev + cur;
    });

    var random_num = rand(0, total_weight);
    var weight_sum = 0;
    //console.log(random_num)

    for (var i = 0; i < choose.length; i++) {
        weight_sum += weight[i];
        weight_sum = +weight_sum.toFixed(2);

        if (random_num <= weight_sum) {
            return choose[i];
        }
    }
    // end of function, modify the weights of list again
       newWeights();
};

  // for the first time pick a city randomaly
  var random_item = getRandomItem(choose[0], choose[2]);
  console.log(random_item);

newWeights();

// after the first time of picking cities let's modify the weights of list
function newWeights(){
var baseDistance = liste.find(l => l.name == random_item).distance;

var list = liste.map(c => {
  console.log();
  var newWeight = Math.abs(baseDistance - c.distance);
  return {
    name: c.name,
    distance: c.distance,
    weight: newWeight
  };
});
liste = list;
 choose = [liste.map(x=>x.name), liste.map(x=>x.distance), liste.map(x=>x.weight)];
console.log(list);
}

// use the modified list to randomaly picking another city
 for (var i = 1; i < repeatTimes; i++) {        
       var random_item = getRandomItem(choose[0], choose[2]);
       console.log(random_item);          
 }