也許有人知道如何通過數組的函數更改對象中的某些數據?JavaScript。如何通過函數更改數組中的某些數據?
例如,我有一個對象:
var nodes = [
{ topic: "Games", topicscore: 100},
{ topic: "Fun", topicscore: 550},
{ topic: "New York", topicscore: 7799},
{ topic: "Hillary", topicscore: 745},
{ topic: "Politics", topicscore: 512},
{ topic: "Trump", topicscore: 71}
];
而且我有一個函數:
var filterScoreValues = function(array_input){
var a_out = [];
array_input.forEach(function(x){
a_out.push(Math.ceil(x/Math.max.apply(null,array_input) * 10) + 5)
});
return a_out;
};
我怎麼能這個算法應用到我的對象的topicscore
?
我寫了這一點,但我希望有一個 「漂亮」 的變種,也許通過lodash或類似:在我的變種
function filterScoreValues(input){
var array = input.map(function (i) {
return i.topicscore;
});
array.forEach(function(x, index){
input[index]['topicscore'] = Math.ceil(x/Math.max.apply(null, array) * 10) + 5;
});
return input;
};
我經常使用的環路.. :(
什麼是你真正想幹什麼?你只需要執行'Math.max.apply(null,array)'一次,而不是每次循環。 – RobG
提供filterScoreValues方法的預期輸出將會有所幫助。 –