检查复选框值生成的数组是否与使用jQuery的预定数组设置匹配

时间:2018-04-03 08:25:46

标签: jquery arrays

我有一组用户将通过单选按钮回答的多项选择题。根据他们的选择,他们将获得与所述选择相关的信息。

我使用map函数观看表单并以数组形式捕获答案:

$('.subscription-builder input[type="radio"]').on('change', function() {
  var results = $('input[type="radio"]:checked').map(function() {
    return this.value;
  }).get();

  var arrayTestOne = ["Cheese", "Carrot", "Lettuce", "Apple"];
  var arrayTestTwo = ["Banana", "Avocado", "Lettuce", "Pear"];

  if (results == arrayTestOne) {
    console.log('WOOOO!');
  } else if (results == arrayTestTwo) {
    console.log('Hooray!');
  }

});

这样做效果不错,但是在输入答案后,我无法确定如何检查它们是否与预定数组相匹配。以下是我尝试过但没有成功的事情:

node -v
8.11.1  

npm -v
5.6.0

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果要检查数组是否相同且顺序相同,可以选择一个选项.join(",")数组。



var results = ["Cheese", "Carrot", "Lettuce", "Apple"]; //TEMP CODE. 

var arrayTestOne = ["Cheese", "Carrot", "Lettuce", "Apple"];
var arrayTestTwo = ["Banana", "Avocado", "Lettuce", "Pear"];

if (results.join(",") == arrayTestOne.join(",")) {
  console.log('WOOOO!');
} else if (results.join(",") == arrayTestTwo.join(",")) {
  console.log('Hooray!');
}




如果您想要检查甚至不按顺序检查,可以使用every



var results = ["Cheese", "Apple", "Carrot", "Lettuce"]; //TEMP CODE. 

var arrayTestOne = ["Cheese", "Carrot", "Lettuce", "Apple"];
var arrayTestTwo = ["Banana", "Avocado", "Lettuce", "Pear"];

if (results.every(o => arrayTestOne.includes(o))) {
  console.log('WOOOO!');
} else if (results.every(o => arrayTestTwo.includes(o))) {
  console.log('Hooray!');
}