jQuery - 比较数组中的indexOF

时间:2017-03-15 17:08:51

标签: javascript jquery arrays indexof

如果我的问题很愚蠢,我想提前道歉,但我对jQuery很新。我想要实现的是比较两个变量。第一个将从div中获取其价值。第二个将是一个数组。如果有人能给我提示我的错误,我将非常感激。提前谢谢。

致以最诚挚的问候,乔治

var User  = $('.User').text();
var Lucky_Names = ["Florence", "Brenda", "Steven"];
console.log(Lucky_Names);

if(User.indexOf(Lucky_Names) >= 1){
  alert("Congratulations, we found a match.");
}
else{
  alert("We couldn't find a match.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="User">Mark Watts</div>
<div class="User">Wanda Hathaway</div>
<div class="User">Ann Bailes</div>
<div class="User">Hal Piccirillo</div>
<div class="User">Richard Branson</div>
<div class="User">Jeffery Robison</div>
<div class="User">Christina Hammons</div>
<div class="User">Helen Clarke</div>
<div class="User">Terra Herrera</div>
<div class="User">Steven Rhodes</div>
<br>
<div style="color:red">PS: All the names in this list were randomly generated.</div>

5 个答案:

答案 0 :(得分:3)

您无法使用User.indexOf(Lucky_Names)

编辑:此外,您的User将是输入,而Lucky_Users包含3个元素。您也可以使用Lucky_Names.indexOf(User) > -1

我相信您要实现的目标是在User

中找到Lucky_Names位置

您需要提供带Lucky_Names

的索引
var position=-1;
for(var i=0;i<Lucky_Names.length;i++) {
  if(Lucky_Names[i] === User) {
    position=i;
  }
}
console.log(position)

如果UserLucky_Names中的任何一个匹配,则位置将是Lucky_Names中的索引,否则它将是-1

答案 1 :(得分:2)

您必须使用.User循环遍历每个jQuery.each元素,并且更容易使数组成为正则表达式或从中创建一个正则表达式:

var Lucky_Names = ["Florence", "Brenda", "Steven"];

var regex = new RegExp(Lucky_Names.join('|')); // regex: /Florence|Brenda|Steven/ (must be escaped if there is special characters)

$('.User').each(function() {                   // for each .User element
  var text = $(this).text();                   // get the text
  if(regex.test(text)) {                       // check if the regex matchs
    $(this).addClass("highlight");
  }
});
.highlight {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="User">Mark Watts</div>
<div class="User">Wanda Hathaway</div>
<div class="User">Ann Bailes</div>
<div class="User">Hal Piccirillo</div>
<div class="User">Florence Branson</div>
<div class="User">Jeffery Robison</div>
<div class="User">Christina Hammons</div>
<div class="User">Helen Clarke</div>
<div class="User">Terra Herrera</div>
<div class="User">Steven Rhodes</div>
<br>
<div style="color:red">PS: All the names in this list were randomly generated.</div>

答案 2 :(得分:2)

您可以使用jQuery.grep进行迭代  position: relative个元素,.User.some()来过滤元素的.indexOf()

.textContent
var Lucky_Names = ["Florence", "Brenda", "Steven"];
var matches = $.grep($(".User"), function(user) {
  return Lucky_Names.some(function(prop) {
  return user.textContent.indexOf(prop) > -1
  });
});

if (matches.length) {
  // do stuff
  $.each(matches, function() {
    this.style.color = "green"
  })
}

您也可以使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="User">Mark Watts</div> <div class="User">Wanda Hathaway</div> <div class="User">Ann Bailes</div> <div class="User">Hal Piccirillo</div> <div class="User">Richard Branson</div> <div class="User">Jeffery Robison</div> <div class="User">Christina Hammons</div> <div class="User">Helen Clarke</div> <div class="User">Terra Herrera</div> <div class="User">Steven Rhodes</div> <br> <div style="color:red">PS: All the names in this list were randomly generated.</div>

.filter()
var Lucky_Names = ["Florence", "Brenda", "Steven"];
var matches = $(".User").filter(function(index, user) {
  return Lucky_Names.some(function(prop) {
  return user.textContent.indexOf(prop) > -1
  });
});

if (matches.length) {
  // do stuff
  matches.each(function() {
    this.style.color = "green"
  })
}

答案 3 :(得分:2)

$('.User').text()将返回在一个字符串中连接的所有名称,如下所示:

"Mark WattsWanda HathawayAnn BailesHal PiccirilloRichard BransonJeffery RobisonChristina HammonsHelen ClarkeTerra HerreraSteven Rhodes"

查找此字符串是否包含Lucky_Names中的任何名称:

var User  = $('.User').text();
var Lucky_Names = ["Florence", "Brenda", "Steven"];
console.log(Lucky_Names);

var _foundFlag = false;
Lucky_Names.forEach( function (d) {
    if (User.indexOf(d) > -1) //Note that 0 is also a positive match
        _foundFlag = true;
})

if (_foundFlag) {
    alert("Congratulations, we found a match.");   
} else {
    alert("We couldn't find a match.");
}

答案 4 :(得分:1)

这可以解决您的问题+也提醒哪些用户是幸运的。既然你是jQuery的新手,也可能是Javascript的新手,我会试着解释一下我做了什么。

  1. 将变量usersluckyNamesluckyUsers声明为const(常量值,因为它永远不会被重新分配)MDN Docs - const

  2. 使用$('.User') MDN Docs - Array.from

  3. Array.from(...)选择器的结果转换为数组
  4. 我正在使用map函数创建一个新数组,其中包含对users数组MDN Docs - map内每个项目应用操作的结果。另请查看MDN Docs - arrow functions以了解user => {...}

  5. 之后我正在应用filter功能,它将为我过滤幸运用户。这发生在函数内部,我检查第一个名称(在这里应用按空格分割得到它)是否在我的luckyNames数组MDN Docs - filter内。

  6. 最后,我检查luckyUsers数组(仅包含已过滤的匹配项)的长度是否大于0.

  7. 为了很好地提醒一切,我正在使用允许我嵌入表达式MDN Docs - template literals的模板文字。

  8. 在模板文字中,我使用join(...)来显示由,和空格MDN Docs - join分隔的匹配名称。

  9. 要查看join(...)的工作原理,只需更改/添加列表中的名称即可。

  10. const users = Array.from($('.User'));
    const luckyNames = ["Florence", "Brenda", "Steven"];
    
    const luckyUsers = users.map(user => {
      return user.innerHTML.replace(/<[^>]*>/, '');
    }).filter(user => {
      return luckyNames.indexOf(user.split(' ')[0]) > -1;
    });
    
    if(luckyUsers.length > 0){
      alert(`Congratulations, we found a match: ${luckyUsers.join(', ')}`);
    } else{
      alert("We couldn't find a match.");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="User">Mark Watts</div>
    <div class="User">Wanda Hathaway</div>
    <div class="User">Ann Bailes</div>
    <div class="User">Hal Piccirillo</div>
    <div class="User">Richard Branson</div>
    <div class="User">Jeffery Robison</div>
    <div class="User">Christina Hammons</div>
    <div class="User">Helen Clarke</div>
    <div class="User">Terra Herrera</div>
    <div class="User">Steven Rhodes</div>
    <br>
    <div style="color:red">PS: All the names in this list were randomly generated.</div>