javascript Javascript从数组列表中获取特定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46576351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:47:01  来源:igfitidea点击:

Javascript get specific values from array list

javascripthtmlarrays

提问by bernlt

<select name="List" id="List">
    <option value="">-Select-</option>
    <option value="">--Product--</option>
    <option value="">product1</option>
    <option value="">product2</option>
    <option value="">product3</option>
    <option value="">--Software--</option>
    <option value="">software1</option>
    <option value="">software2</option>
    <option value="">software3</option>
    <option value="">--Services--</option>
    <option value="">service1</option>
    <option value="">service2</option>
    <option value="">service3</option>
</select>

I have the above List on my HTML select field.

我的 HTML 选择字段中有上述列表。

I want to be able to get only the values --Product--, --Software--, --Services-- So I created an loop to go throw the list of products and used the method startwith to pickup the values starting with "--".

我希望能够只获得值 --Product--、--Software--、--Services-- 所以我创建了一个循环来抛出产品列表并使用方法 startwith 来获取以“——”。

function loadFilter() {
  var x = document.getElementById('List');
  var i;
  var n;
  for (i = 0; i < x.length; i++) {
    str = x[i].text
    var n = str.startsWith('--');
    flag = true;
    if (n == true) {
      alert(x[i].text);   // list --Product--, --Software--, --Services--
      alert(x[3].text);   // prints from the LIST <product1> and not <--Services-->
    }
  }
}

So when the flag is true, the alert(x[i].text);list correctly the values (--Product--, --Software--, --Services--).

因此,当标志为真时,将alert(x[i].text);正确列出值(--Product--、--Software--、--Services--)。

But when I try to get them by their values(index), E.G ..I need to get only (--Services--), so I use x[3].text), but this returns me the whole List values >> and not <--Services-->.

但是当我尝试通过它们的值(索引)获取它们时,EG ..我只需要获取(--Services--),所以我使用x[3].text),但这会返回整个 List 值 >> 而不是 <--Services -->.

采纳答案by Aanand Kainth

Here you go:

干得好:

function loadFilter() {
    var element = document.getElementById('List');
    var children = element.children;
    var filtered = [];
    for (var i = 0; i < children.length; i++) {
        if (children[i].textContent.startsWith('--')) {
            filtered.push(children[i].textContent);
        }
    }
    return filtered;
}

To recap what the function did:

回顾一下该函数的作用:

  1. Get the element "List"
  2. Get the children of "List"
  3. Create an array to hold elements that pass the filter
  4. Go through each element and add those with match the specified regex
  5. Return the elements that pass the filter
  1. 获取元素“列表”
  2. 获取“列表”的孩子
  3. 创建一个数组来保存通过过滤器的元素
  4. 遍历每个元素并添加与指定正则表达式匹配的元素
  5. 返回通过过滤器的元素

回答by Phani Kumar M

You can use the below code to populate array arrwith the list of options having "--".

您可以使用以下代码使用arr带有“--”的选项列表填充数组。

Then you can use arr[2]to get --Services--.

然后你可以使用arr[2]获取--Services--.

var arr = [];
[].slice.call(document.querySelectorAll("#List option")).map(function(el){
    if (el.text.indexOf("--") === 0) arr.push(el.text);
});

console.log(arr)
console.log(arr[2])
<select name="List" id="List">
    <option value="">-Select-</option>
    <option value="">--Product--</option>
    <option value="">product1</option>
    <option value="">product2</option>
    <option value="">product3</option>
    <option value="">--Software--</option>
    <option value="">software1</option>
    <option value="">software2</option>
    <option value="">software3</option>
    <option value="">--Services--</option>
    <option value="">service1</option>
    <option value="">service2</option>
    <option value="">service3</option>
</select>

回答by Carlos Augusto Grispan

First of all, you don't seen to be using your flag at all.

首先,您根本没有看到使用您的标志。

If I understood it correctly, you are trying to get --Services-- using x[3].text, but if you count your whole list the element at index [3] is the . You can verify that with the code bellow:

如果我理解正确,您正在尝试使用 --Services-- using x[3].text,但是如果您计算整个列表,则索引 [3] 处的元素是 . 您可以使用以下代码进行验证:

f (n == true) {
  alert('index '+ i + ': ' + x[i].text);   // list --Product--, --Software--, --Services--
}

You could create a new array containing the filtered options and then access the with the known index:

您可以创建一个包含过滤选项的新数组,然后使用已知索引访问:

var filteredArray = [];
f (n == true) {
  filteredArray.push(x[i]); //insert the element in the new array.
}
alert(filteredArray[2].text) //print --Service--, the third element of filtered array.

Remember that javascript has zero indexed array, so the first element has index 0, so, in order to acces the third element you'll need the index 2.

请记住,javascript 的索引数组为零,因此第一个元素的索引为 0,因此,为了访问第三个元素,您需要索引 2。

回答by CJ Nimes

May be you want to try using optgroups?

可能你想尝试使用optgroups

Something like this:

像这样的东西:

<select name="List" id="List">

    <option value="">-Select-</option>

    <optgroup label="--Product--">
        <option value="">product1</option>
        <option value="">product2</option>
        <option value="">product3</option>
    </optgroup>

    <optgroup label="--Software--">
        <option value="">software1</option>
        <option value="">software2</option>
        <option value="">software3</option>
    </optgroup>

    <optgroup label="--Services--">
        <option value="">service1</option>
        <option value="">service2</option>
        <option value="">service3</option>
    </optgroup>

</select>

Then,

然后,

var select = document.getElementById('List');
var optgroups = select.getElementsByTagName('optgroup');

console.log(optgroups[2].label);

Will show:

将会呈现:

--Services--

回答by merlin

try:

尝试:

function load() { 
    list = document.getElementById('List');
    var data = document.getElementsByTagName('option');
    currentCatagory=null;//the current selected catagory
    currentvalue=null;
    listdata=[];
    
    //for all the options 
    for(cnt = 0; cnt < data.length; cnt++){
        var e = data[cnt].innerHTML;//get option text
        if(e.startsWith('-')){//test to make a catagory out of it
            if(currentCatagory!=null)//do not concat is listdata is null
                listdata=listdata.concat(currentCatagory);
            currentCatagory = {"this":e,"listOfItems":[]};//create the catagory
        }else if(currentCatagory!=null){//make sure currentCatagory is not null
            var l=currentCatagory.listOfItems;//get the Catagory's list
            currentCatagory.listOfItems = l.concat(e);//and add e
        }
    }
    listdata=listdata.concat(currentCatagory);//add  last catagory
    //sets the list to show only catagories
    var inner='';
    for (i = 0; i < listdata.length; i++) {
        inner+=parseOp(listdata[i].this);
    }
    list.innerHTML=inner;
}
    function update(){
    //check to make sure everything is loaded
        if(typeof list=='undefined'){
            load();
        }
        
        var inner='';//the new  options
        var value=list.options[list.selectedIndex].innerHTML;
        if(value==currentvalue) return;
        if(value.startsWith('-')){//if catagory
            if(value.startsWith('--')){//if not -Select-
                for (i = 0; i < listdata.length; i++) {//for all catagories 
                    if(value==listdata[i].this){//if it is the current selected catagory then...
                        currentCatagory=listdata[i];//update the currentCatagory object
                        inner+=parseOp(listdata[i].this);//parse as option and append
                        //then append catagory's items
                        for(item in listdata[i].listOfItems){
                            inner+=parseOp(listdata[i].listOfItems[item]);
                        }
                    }else{//appends the other catagories
                        inner+=parseOp(listdata[i].this);
                    }
                }
            }else{//if it is '-select-' then just append the catagories
                for (i = 0; i < listdata.length; i++) {
                    inner+=parseOp(listdata[i].this);
                }
            }
            //set the new options
            list.innerHTML=inner;
        }
    }
    function parseOp(str){
    //parse the options
     return '<option value="">'+str+'</option>';
    }
<select name="List" id="List" onchange="update();">
    <option value="">-Select-</option>
    <option value="">--Product--</option>
    <option value="">product1</option>
    <option value="">product2</option>
    <option value="">product3</option>
    <option value="">--Software--</option>
    <option value="">software1</option>
    <option value="">software2</option>
    <option value="">software3</option>
    <option value="">--Services--</option>
    <option value="">service1</option>
    <option value="">service2</option>
    <option value="">service3</option>
</select>

and to set the dropdown box you will have to run load()otherwise load()will only be called after the first change event occurs.

并设置下拉框,您必须运行,load()否则load()只会在第一个更改事件发生后调用。

回答by Mizstik

I'm still not entirely sure what you're trying to do. --Services-- is index 9, not 3. To get --Services-- you need x[9].text

我仍然不完全确定你想要做什么。--Services-- 是索引 9,而不是 3。要获得 --Services-- 你需要x[9].text

If you want to rearrange the three --xx-- into their own index, you need to push them into a new array, like so:

如果你想将三个 --xx-- 重新排列到它们自己的索引中,你需要将它们推送到一个新的数组中,如下所示:

var output = []
if (n === true) output.push(x[i].text)
console.log(output[2]) // --Services--

回答by pegla

You can use simple forEach loop to loop through elements like here, but first you need to create Array from your DOM Node list:

您可以使用简单的 forEach 循环来像这里一样循环遍历元素,但首先您需要从 DOM 节点列表创建数组:

  var list = Array.from(x);
  list.forEach((value,index)=>{
    if (value.text.startsWith('--')){
      alert(value.text);
    }
  });

I've put it up on fiddle so you can check: https://jsfiddle.net/pegla/qokwarcy/

我已经把它放在小提琴上,所以你可以检查:https: //jsfiddle.net/pegla/qokwarcy/