-2

我想生成一个介于 0 和 1 之间的成比例的数字数组,其中包含一个具有不同大小值的销售额数组。

例如,如果我有值[1, 80, 2000],则可以使用类似[0.1, 0.4, 1].

4

2 回答 2

3

a modern functional approach:

var r=[1, 80, 2000] ;

r.map(function(a){
   return a/this;
}, Math.max.apply(0,r) );

//==[0.0005,0.04,1]

i think math was off in OP...

edit: details on what's going on here: The problem is broken down into two steps.

  1. find the largest number in the Array
  2. compute each Array item as a portion of the largest item

For the first step, JS provides the Math.max function. To use an argument-based function with an array, the function's apply() method is used, and 0 is passed as "this", but it's not really used; it just needs to be something.

The second step compares each item to the number found in step #1, using the Array.map method to iterate the Array and return the result of an operation upon each item in the Array. Since Array.map() can accept an optional "this" argument, the largest number from step #1 is passed as "this" to avoid a performance-robbing function closure.

于 2013-05-06T16:37:38.870 回答
0

虽然不清楚,但原始数组和生成的数组之间应该是什么关系。我假设您要创建项目在总和(比例)中的比例:

尝试这个:

function generateProportion(arr){

    //find out the total sum..
    var total = 0;
     for(var k=0;k <arr.length;k++)
         total += arr[k];

    //push the ratios into the new array with double precison..
    var newArr = new Array();

    for(var i=0;i< arr.length; i++)
        newArr.push((arr[i]/total).toFixed(2));

    console.log(newArr);
    return newArr;
}

并这样称呼它:

var a = [1, 80, 2000];
generateProportion(a);

看到这个小提琴

于 2013-05-06T16:31:03.853 回答