我想找到一個物件內 2 個值之間的數值差異。
我的物件是這樣完成的:
{ today: 9, lastMonth: 6 }
我在 every() 方法中:
const validation = Object.values(myObj).every(item => console.log(item))
every 方法都在 reduce() 方法中,因為我有一個物件陣列,就像我在這里寫的那樣。
現在專案日志正在列印與前一個物件沒有任何聯系的值,但是一個接一個,所以似乎我不能像這樣對值進行區分:
function difference(a, b) {
return Math.abs(a - b);
}
我的期望:
(item => difference(item))
找出我的物件中存在的 2 個值之間的差異
怎么了:
差異回傳 NaN,因為專案沒有放在一起
編輯:我解決了主要問題,現在我有一個簡單的陣列,如下所示:
[[0,2],[4,9],[5,7]]...
似乎 Math.abs(ab) 不適用于陣列,有有效的解決方案嗎?
uj5u.com熱心網友回復:
如果您在spread syntax (...)呼叫差異函式時使用 ,結果應該符合預期。
我建議創建一個包裝getDifferences()函式來實作這一點:
function difference(a, b) {
return Math.abs(a - b);
}
function getDifferences(arr) {
return arr.map(el => difference(...Object.values(el)));
}
console.log(getDifferences([{ today: 9, lastMonth: 6 }]));
console.log(getDifferences([[0,2],[4,9],[5,7]]));
console.log(getDifferences([{ a: 1, b: 2 }, { x: 1, y: 3 }]));
.as-console-wrapper { max-height: 100% !important; }
您也可以使用function.apply,這也將允許您將引數陣列傳遞給函式:
function difference(a, b) {
return Math.abs(a - b);
}
function getDifferences(arr) {
return arr.map(el => difference.apply(null, Object.values(el)));
}
console.log(getDifferences([{ today: 9, lastMonth: 6 }]));
console.log(getDifferences([[0,2],[4,9],[5,7]]));
console.log(getDifferences([{ a: 1, b: 2 }, { x: 1, y: 3 }]));
.as-console-wrapper { max-height: 100% !important; }
uj5u.com熱心網友回復:
嘗試
function difference(array) {
var result = [];
for(var i=0;i<array.length;i ){
result.push(Math.abs(array[i][0]-array[i][1]));
}
return result
}
var arr = [[0,2],[4,9],[5,7]]
console.log(difference(arr))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455817.html
標籤:javascript 数组 反应 目的
