我在螢屏上選擇了值,它們的值存盤在兩個變數中。
var uval = '100';
var eval = '5';
有 2 種組合具有值:
let combination1= 'u:100;e:1,4,5,10'
let combination2 = 'u:1000;e:120,400,500,1000'
我想檢查 uval 和 eval 是否存在于任何組合中,并將一些布林值設定為 true,否則它將為 false。uval 將與該組合中的 u 進行比較,并在該組合中將 eval 與 e 進行比較。
此示例中的布林值將為真。如果 uval='50'; eval='5' 那么它將是錯誤的。
我嘗試使用 split(';') 使用 for 回圈,并將每個 u 與 uval 和 e 與 eval 進行比較。除了每次都使用傳統的 for 回圈之外,我正在為此尋找一些不同的方法。
uj5u.com熱心網友回復:
你可以做這樣的事情
基本上我創建了一個函式,將你的組合轉換為一個物件,我在檢查函式中使用了該物件
const combination1= 'u:100;e:1,4,5,10'
const combination2 = 'u:1000;e:120,400,500,1000'
const uval = '100';
const eval = '5';
const toObject = combination => Object.fromEntries(
combination.split(';').map(c => c.split(':')).map(([k, v]) => [k, v.split(',')])
)
const check = (combination, key , value ) => (toObject(combination)[key] || []).includes(value)
const checkEval = (combination, eval) => check(combination, 'e', eval)
const checkUval = (combination, uval) => check(combination, 'u', uval)
console.log(checkEval(combination1, eval))
console.log(checkEval(combination2, eval))
console.log(checkUval(combination1, uval))
console.log(checkUval(combination2, uval))
uj5u.com熱心網友回復:
我創建了一個名為getKeyValuePairs回傳給定組合的鍵值對的函式。
因此,如果我們getKeyValuePairs使用組合呼叫,"u:100;e:1,4,5,10"它將回傳以下鍵值對陣列:
[
[ 'u', [ '100' ] ],
[ 'e', [ '1', '4', '5', '10' ] ]
]
然后我創建了另一個名為的函式groupCombinations,它將傳遞給它的所有組合合并到一個物件中。
因此,如果我們groupCombinations使用組合呼叫"u:100;e:1,4,5,10"and "u:1000;e:120,400,500,1000",它將回傳以下物件:
{
u: Set(2) {"100", "1000"},
e: Set(8) {"1", "4", "5", "10", "120", "400", "500", "1000"}
}
最后,我使用 將所有組合組合在一起groupCombinations,然后檢查該組是否包含uValand eVal。
const getKeyValuePairs = (combination) =>
combination
.split(";")
.map((str) => str.split(":"))
.map(([k, v]) => [k, v.split(",")]);
const groupCombinations = (...combinations) =>
Object.fromEntries(
Object.entries(
combinations.reduce(
(group, combination) => (
getKeyValuePairs(combination).forEach(([k, v]) =>
(group[k] ??= []).push(...v)
),
group
),
{}
)
).map(([k, v]) => [k, new Set(v)])
);
const uVal = "100";
const eVal = "5";
const combination1 = "u:100;e:1,4,5,10";
const combination2 = "u:1000;e:120,400,500,1000";
const allCombinations = groupCombinations(combination1, combination2);
const isUVal = allCombinations["u"].has(uVal);
const isEVal = allCombinations["e"].has(eVal);
const isBoth = isUVal && isEVal;
console.log(isBoth);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488829.html
標籤:javascript 数组 反应 有角度的 细绳
上一篇:我們可以使用任何預定義的函式和正則運算式替換字串文字的特定部分嗎
下一篇:有條件地替換字串中的子字串
