如何检查数组中的项目,如:
var dayPartsArr = ['PT','WDM','WDD','EF','WKE'];
也是对象中的键,例如:
var dayPartsMap = {
'PT': 'PRIME TIME',
'WDM': 'WEEKDAY MORNING',
'WDD': 'WEEKDAY DAYTIME',
'EF': 'EARLY FRINGE',
'WKE': 'WEEKEND DAYTIME'
};
请紧记dayPartsArr
的顺序无关紧要。因此,如果
var dayPartsArr = ['WKE','PT','WDM','WDD','EF'];
我仍然希望能够使用dayPartsMap
来检查dayPartsArr
中的每个项目是否是dayPartsMap
中的键
答案 0 :(得分:2)
忽略顺序,我们可以采用输入数组并将其与键进行比较,如下所示:
var dayPartsArr = ['WDM','PT','WDD','EF','WKE']; //out of order
var dayPartsMap = {
'PT': 'PRIME TIME',
'WDM': 'WEEKDAY MORNING',
'WDD': 'WEEKDAY DAYTIME',
'EF': 'EARLY FRINGE',
'WKE': 'WEEKEND DAYTIME'
};
dayPartsArr.every(item => ~Object.keys(dayPartsMap).indexOf(item)); // true
// Compare against an array with a missing key
dayPartsArr = ['WDM','PT','FAKE', 'WDD','EF','WKE'];
dayPartsArr.every(item => ~Object.keys(dayPartsMap).indexOf(item)); // false
请注意,
~
是bitwise NOT operator,它有助于indexOf
您可以将对象的键转换为数组,然后比较该数组,如下所示:
有关Object.keys的更多信息,check MDN here.
var dayPartsArr = ['PT','WDM','WDD','EF','WKE'];
var dayPartsMap = {
'PT': 'PRIME TIME',
'WDM': 'WEEKDAY MORNING',
'WDD': 'WEEKDAY DAYTIME',
'EF': 'EARLY FRINGE',
'WKE': 'WEEKEND DAYTIME'
};
// Create the comparison function...
function arraysIdentical(a, b) {
var i = a.length;
if (i != b.length) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
};
/// compare!
arraysIdentical(dayPartsArr, Object.keys(dayPartsMap)); // true
arraysIdentical
最初由Tim Down
答案 1 :(得分:0)
我们可以使用every
和filter
解决此问题。
参考:
var dayPartsArr = ['PT','WDM','WDD','EF','WKE'];
var dayPartsMap = {
'PT': 'PRIME TIME',
'WDM': 'WEEKDAY MORNING',
'WDD': 'WEEKDAY DAYTIME',
'EF': 'EARLY FRINGE',
'WKE': 'WEEKEND DAYTIME',
};
// > 1 for WKE
// var dayPartsArr = ['PT','WDM','WDD','EF','WKE', 'WKE'];
const check = Object.keys(dayPartsMap).every(key => dayPartsArr.filter(day => day === key).length === 1);
console.log(check);
答案 2 :(得分:0)
您可以使用Array.prototype.every
检查dayPartsArr
键中是否存在dayPartsMap
的所有项目:
var dayPartsArr = ['PT','WDM','WDD','EF','WKE'];
var dayPartsMap = { 'PT': 'PRIME TIME', 'WDM': 'WEEKDAY MORNING', 'WDD': 'WEEKDAY DAYTIME', 'EF': 'EARLY FRINGE', 'WKE': 'WEEKEND DAYTIME' };
var objKeys = Object.keys(dayPartsMap);
var result = dayPartsArr.every(day => objKeys.includes(day));
console.log(result);