我有兩個要比較的陣列。每個物件的狀態可以是 true、false 或 null,具體取決于用戶選擇的內容。
然后我想比較兩個陣列,如果它們相互匹配,則將活動的名稱推送到一個單獨的陣列中。
例如,如果它比較第一個是“免費”的,并且用戶已經檢查了這一點,使 { free: true } ,那么這個活動(“去電影院”)將不會被推送到新陣列中。
//user input
filtersChecked: [
{ free: null },
{ indoors: null },
{ city: null },
{ winter: null },
{ physical: null },
],
//compared against:
name: "Go to the cinema",
filters: [
{ free: false },
{ indoors: true },
{ city: true },
{ winter: null },
{ physical: false },
],
我正在努力比較物件狀態的“索引”,如果這有意義的話......
我的嘗試看起來像這樣:
function checkFilter(index, isChecked) {
if (isChecked) {
model.input.filtersChecked[index] = true;
} else if (!isChecked) {
model.input.filtersChecked[index] = false;
}
}
function suggestActivities() {
let userFilters = model.input.filtersChecked;
let activityFilters;
let tempArray = [];
for (let i = 0; i < model.data.activities.length; i ) {
activityFilters = model.data.activities[i].filters;
for (let j = 0; j < userFilters.length; j ) {
if (userFilters[j] === activityFilters[j]) {
tempArray.push(model.data.activities[i].name);
console.log(tempArray);
continue;
}
}
}
console.log(tempArray);
}
我希望它足夠詳細。卡在這個問題上太久了。
還值得一提的是,我希望它是普通的 JavaScript,因為這是一項學校作業。所以請不要使用jQuery!
先感謝您!
uj5u.com熱心網友回復:
這是一個如何進行比較的示例,您可以將其分解為子問題。將其用作如何解決作業問題的模板。如果有幫助,請告訴我。
const userInput = [
{ free: null },
{ indoors: null },
{ city: null },
{ winter: null },
{ physical: null },
]
const compared = {
name: "Go to movies"
filters: [
{ free: false },
{ indoors: true },
{ city: true },
{ winter: null },
{ physical: false },
]
}
const tempArr = []
function compareObjects (userInput, compared) {
//loop through userInput filters
for (let i=0; i<userInput.length; i ){
//grab key from current index of array (like "free", "indoors", etc)
let key = Object.keys(userInput[i])[0]
//compare stored filters with user filters
//if not equal, we can stop searching through the filters entirely and exit the function,
// since if one of them doesnt match, we wont push at all
//Note, I can reuse the userInput key for the compared keys, because both arrays are of equal length.
//If they weren't the same length, the keys wouldn't match, and you would have to sort the array first
//so the index order and keys matched for both inputs.
if(userInput[i][key] !== compared.filters[i][key]) return
}
// if we made it through this loop without exiting the function, we can
// push the name since it means they all matched
tempArr.push(compared.name)
}
//call the function and pass in variables
compareObjects(userInput, compared)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367542.html
