使用数组中左右值的平均结果填充数组

时间:2015-07-06 06:27:22

标签: javascript arrays

我有一个像这样的数组

var salaries=[30000,undefined,40000,50000,undefined,70000] 

这里我希望用左右值的平均值填充未定义的值。像这样。

modified_salaries=[30000,35000,40000,50000,60000,700000]

实际上,我尝试了很多次并且为实现这一点而感到困惑。

请帮帮我,这种计算有没有解决办法。

编辑:如果数组是

var salaries=[30000,undefined,undefined,40000,50000,undefined,70000]

结果应该是:

modified_salaries=[30000,33000,36000,40000,50000,60000,70000]

4 个答案:

答案 0 :(得分:3)

请参阅代码中的内联注释:

var salaries = [30000, undefined, 40000, 50000, undefined, 70000];

var modified_salaries = []; // Define empty array

for (var i = 0; i < salaries.length; i++) {
    if (salaries[i]) {
        modified_salaries.push(salaries[i]); // If not undefined, push it as it is
    } else {
        // Check if prev and next element exists, use 0 otherwise to calculate average.
        average = ((salaries[i - 1] || 0) + (salaries[i + 1] || 0)) / 2;

        modified_salaries.push(average); // Push average in new array.
    }
}
console.log(modified_salaries); // Log new array

Demo

答案 1 :(得分:2)

试试这个

var salaries = [30000, undefined, 40000, 50000, undefined, 70000]
var modified_salaries = salaries.map(function(x, i) {
    return typeof x === "undefined" ? (salaries[i - 1] || 0 + salaries[i + 1] || 0) / 2 : x;
});

console.log(modified_salaries);

答案 2 :(得分:0)

试试这样:

<div></div>

var salaries=[30000,undefined,40000,50000,undefined,70000];
var modified_salaries = [];

for(var i=0; i<salaries.length; i++) {
    if(salaries[i] === undefined) {
         modified_salaries.push((salaries[i-1] + salaries[i + 1])/2);
    } else {
        modified_salaries.push(salaries[i])     
    }
}

$("div").text(modified_salaries)

Jsfiddle

答案 3 :(得分:0)

可以这样做。

var salaries = [30000, undefined, 40000, 50000, undefined, 70000];

var finalSal = [];

salaries.forEach(function(val, key) {

    if (val) {
        finalSal.push(val);
    } else {
        finalSal.push((salaries[key - 1] + salaries[key + 1]) / 2);
    }
});