Javascript:如何检查数组中的某些项目

时间:2018-07-11 01:30:59

标签: javascript jquery arrays javascript-objects

如何检查数组中的项目,如:

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中的键

3 个答案:

答案 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)

我们可以使用everyfilter解决此问题。

参考:

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);