2015-07-06 60 views
0

我有這樣裝滿平均結果與左,右值數組中的數組

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] 
+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

+0

首先感謝回覆,對我的問題工作正常,但還有另一個要求,即如果薪資數組類似[30000,undefined,undefined,40000,50000,undefined,70000];作爲你的方法結果是[30000,15000,20000,40000,50000,60000,70000]但我想答案像[30000,33000,36000,40000,50000,60000,70000] –

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); 
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

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); 
    } 
});