我按照本教程(https://www.tutorialspoint.com/compare-two-objects-in-javascript-and-return-a-number-between-0-and-100-representing-the-percentage-of-similarity ) 以便能夠在 JavaScript 中比較兩個物件并回傳一個介于 0 和 100 之間的數字,表示相似度的百分比。
但是,這只適用于兩個物件中的精確鍵值對。我還需要能夠比較數字間隔(例如下面的第三個“if”陳述句)。預期的結果是 70,但目前我得到了 80(如果您在第二個之后評論所有“if”陳述句,它會給您 40 作為結果,這是正確的)。
當我寫第三個“if”陳述句并繼續其他陳述句時,我的問題就開始了。實際上,在第三個“if”陳述句之后,其他“if”對最終結果沒有任何影響(我不知道為什么)。有人可以幫忙找到合適的解決方案嗎?
const a = {
especie: 'cachorro',
idade_min: 1,
idade_max: 3,
sexo: 'M',
peso_min: 5,
peso_max: 10,
tamanho: 50,
porte: 100,
cor: 'preta',
ra?a: 'pitbull',
castrado: true,
vacinado: true,
};
const b = {
especie: 'cachorro',
idade: 2,
sexo: 'M',
peso: 10,
tamanho: 25,
porte: 100,
cor: 'branca',
ra?a: 'pitbull',
castrado: false,
vacinado: false,
};
const findMatch = (first, second) => {
const firstLength = Object.keys(first).length;
const secondLength = Object.keys(second).length;
const smaller = firstLength < secondLength ? first : second;
const greater = smaller === first ? second : first;
const count = Object.keys(smaller).reduce((acc, key) => {
let counter = acc;
if (Object.keys(greater).includes(key)) {
if (greater[key] === smaller[key]) {
console.log(counter);
return counter;
};
if (b.idade <= a.idade_max && b.idade >= a.idade_min) {
return counter;
};
if (b.peso <= a.peso_max && b.peso >= a.peso_min) {
return counter;
};
if (b.tamanho <= a.tamanho) {
return counter;
};
if (b.porte <= a.porte) {
return counter;
};
};
console.log(counter);
return counter;
}, 0);
return (count / Math.min(firstLength, secondLength)) * 100;
};
console.log(findMatch(a, b)); // expected result = 70?
uj5u.com熱心網友回復:
你的函式不是動態的,它使用全域范圍內的常量物件值和鍵無論如何檢查它會正常作業我認為
const a = {
especie: 'cachorro',
idade_min: 1,
idade_max: 3,
sexo: 'M',
peso_min: 5,
peso_max: 10,
tamanho: 50,
porte: 100,
cor: 'preta',
ra?a: 'pitbull',
castrado: true,
vacinado: true,
};
const b = {
especie: 'cachorro',
idade: 2,
sexo: 'M',
peso: 10,
tamanho: 25,
porte: 100,
cor: 'branca',
ra?a: 'pitbull',
castrado: false,
vacinado: false,
};
const findMatch = (first, second) => {
const firstLength = Object.keys(first).length;
const secondLength = Object.keys(second).length;
const smaller = firstLength < secondLength ? first : second;
const greater = smaller === first ? second : first;
const smallObjKeys = Object.keys(smaller)
const count = smallObjKeys.reduce((counter, key) => {
// this to check the similarity between normal keys
if (greater[key] === smaller[key])
return counter;
// this to check the similarity between keys have range to compare with
if (smaller[key] <= greater[`${key}_max`] && smaller[key] >= greater[`${key}_min`])
return counter
// just to show you the different key
console.log(`the ${key} is not the same`);
return counter;
}, 0);
return (count / Math.min(firstLength, secondLength)) * 100;
};
console.log(findMatch(a, b)); // expected result = 70?
// WRONG ^^ it's 60%
我認為你對預期的輸出是錯誤的祝你好運
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/496707.html
標籤:javascript 目的 if 语句 相比 javascript 对象