JavaScript 如何使用 NOT 的索引与选择数组

javascript how to use index of not with select array

本文关键字:选择 数组 索引 何使用 NOT JavaScript      更新时间:2023-09-26

我有一个值,称之为a,还有一个id = "sid"的选择框。 我在javascript中,想知道我的值a是否是选择框中的选项之一。

我走到了这一步:HTML:

<select id = "sid">
  <option>a</option>
  <option>b</option>
</select>
<script>
  isThere('sid')
</script>

Javascript:

function isthere(id) {
  var x = document.getElementById(id).options;
  for (j = 0; j<= 1; j++) {
  alert ("arr is " + x[j].text );
} 
var c = x.text.indexOf("a");
  alert ("c is " + c);
}

循环给出了 x[j].text 的正确答案。 我没有得到 c 的值。 Firebug给了我错误"x.text is undefined"。

使用索引的正确方法是什么,找出"a"是否在此选择框中? 在效率方面,我只是循环遍历x.text[j]会更好吗?

如果您有值数组,则可以使用 indexOf

若要获取值数组,可以使用

[].map.call(x, function(option) {
    return option.value;
});

因此,您可以使用

[].map.call(x, function(option) {
    return option.value;
}).indexOf("a");

在 ECMAScript 6 中,你可以将其简化为

[].map.call(x, option => option.value).indexOf("a");

var x = document.getElementById("sid");
alert([].map.call(x, function(option) {
  return option.value;
}).indexOf("a"));
<select id="sid">
  <option>a</option>
  <option>b</option>
</select>

你可以这样做:

function isThere(id, value) {
    return Array.prototype.some.call(document.getElementById(id).options, 
        function (i) { return i.value === value });
}

请注意,我在函数中添加了value参数。

看到小提琴工作。

这样:

    function isThere(id, value) {
        for (i = 0; i < document.getElementById(id).length; ++i){
            if (document.getElementById(id).options[i].value === value){
              return true;
            }
        }
        return false;
    }

这个怎么样:

<HTML>
 <head>
  <script>
   function makeArray(id) {
       var x = document.getElementById(id);
       var arr = [];
       for (var i = 0; i < x.length; i++) {
           arr.push(x.options[i].value);
       }
       return arr;
   }
   function isthere(id) {
    var arr = makeArray(id);
    var c = arr.indexOf("b");
    alert ("c is " + c);
   }
  </script>
 </head>
 <BODY onload="isthere('sid');">
  <select id = "sid">
  <option>a</option>
  <option>b</option>
  </select>
 </body>
</html>

当你x.text.indexOf("a");引用 de 数组 <option> . 否元素的文本。...你也可以 ...

var x = document.getElementById(id).options;

  for (j = 0; j<= 1; j++) {
   if (x[j].text.indexOf("a"){
       alert("it is a");
   }
} 

或 var x = document.getElementById(id).options;

  x.forEach(function (element) {
        if (element.text.indexOf("a")){
            alert("it is a");
        }
  });

你可以使用==而不是那样.indexOf

if (element.text == "a")){
            alert("it is a");
}

如果您尝试显示所选选项的文本,则可以使用以下命令:

function isthere(id) {
  var x = document.getElementById(id).options;
 var c = x[x.selectedIndex].text
 alert ("c is " + c);
 }

indexOf 用于在数组中查找索引,因为 x 是 HTMLOptionsCollection不能使用索引