如何调试此加权随机名称选择器代码

时间:2019-06-26 08:56:28

标签: javascript

这是将根据定义的权重选择一个随机名称的代码。

代码如下:

var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};

var getRandomItem = function(list, 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 < list.length; i++) {
        weight_sum += weight[i];
        weight_sum = +weight_sum.toFixed(2);

        if (random_num <= weight_sum) {
            return list[i];
        }
    }

    // end of function
};


var list = [];
var data = [];

data[0] = { Name: "Jack", accuracy: 52, accent: 79, weight: 1 };
data[1] = { Name: "Sara", accuracy: 92, accent: 24, weight: 2 };
data[2] = { Name: "Nick", accuracy: 82, accent: 89, weight: 1 };
data[3] = { Name: "Doe", accuracy: 22, accent: 88, weight: 4 };
data[4] = { Name: "Lee", accuracy: 58, accent: 63, weight: 9 };
data[5] = { Name: "Sasha", accuracy: 69, accent: 42, weight: 5 };

for ( var i=0; i < data.length; i++ ) {
  list.push( data[i] );

}

  console.log(list);

 setInterval(function(){  

 for ( var i=0; i < data.length; i++ ) {
  var random_item = getRandomItem(list[i].Name, list[i].weight);
  console.log(random_item);

}

}, 500);

不幸的是,由于出现错误,代码无法正常工作

  

未捕获的TypeError:weight.reduce不是函数       在getRandomItem

我不知道为什么会这样。

注意:这将起作用...

var list = ['javascript', 'php', 'ruby', 'python'];
var weight = [1, 1, 1, 9];
var random_item = getRandomItem(list, weight);
console.log(random_item);

1 个答案:

答案 0 :(得分:1)

正如其他人指出的那样,列表和权重参数必须是数组。 因此,我在以下代码中构建了两个数组。

var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};

var getRandomItem = function(list, 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 < list.length; i++) {
        weight_sum += weight[i];
        weight_sum = +weight_sum.toFixed(2);

        if (random_num <= weight_sum) {
            return list[i];
        }
    }

    // end of function
};


var list = [];
var weight = [];
var data = [];

data[0] = { Name: "Jack", accuracy: 52, accent: 79, weight: 1 };
data[1] = { Name: "Sara", accuracy: 92, accent: 24, weight: 2 };
data[2] = { Name: "Nick", accuracy: 82, accent: 89, weight: 1 };
data[3] = { Name: "Doe", accuracy: 22, accent: 88, weight: 4 };
data[4] = { Name: "Lee", accuracy: 58, accent: 63, weight: 9 };
data[5] = { Name: "Sasha", accuracy: 69, accent: 42, weight: 5 };

for ( var i=0; i < data.length; i++ ) {
  list.push( data[i].Name );
  weight.push( data[i].weight );
}

  console.log(list);
  console.log(weight);

 setInterval(function(){  

for ( var i=0; i < data.length; ++i ) {
  var random_item = getRandomItem(list, weight);
  console.log(random_item);
}

}, 500);