javascript 如何循环遍历javascript中的子对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17094230/
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-27 07:04:02  来源:igfitidea点击:

How do I loop through children objects in javascript?

javascript

提问by Corey Ray

I have this code in a function:

我在一个函数中有这个代码:

tableFields = tableFields.children;
for (item in tableFields) {
    // Do stuff
}

According to a console.log of tableFields, I am getting an array back as I assume I need to do. A console.log of item within the loops returns undefined. What do I have to do to loop through tableFields and insert each object into a table?

根据 tableFields 的 console.log,我得到了一个数组,因为我认为我需要这样做。循环中 item 的 console.log 返回 undefined。我该怎么做才能遍历 tableFields 并将每个对象插入到表中?

console log of tableFields:

tableFields 的控制台日志:

HTMLCollection[label, input, label, input 25, label, input, input, input Remove]


0
label

1
input

2
label

3
input 25

4
label

5
input

6
input

7 
input Remove

description[]
input

hours[]
input

invoice_number
input

getlength
8

rate[]
input 25

item
item()

iterator
iterator()

namedItem
namedItem()

__proto__
HTMLCollectionPrototype { item=item(), namedItem=namedItem(), iterator=iterator()}

Here is the entire section of code as I have so far:

这是我到目前为止的整个代码部分:

$this->title("Test");
    $this->defaultMenu();
    $select = "";
    $names = Customer::getNames();
    foreach ($names as $id => $name) {
        $select .= '<option value="'.$id.'"';
        if ($this->customerid == $id) $select .= ' selected ';
        $select .= '>'.$name.'</option>';
    }

    $form = '
<script type="text/javascript">

var counter = 0;

function isEven(int){
int = Number(int);
return (int%2 == 0);
}



function moreLabor() {

    var table = document.getElementById("editTable");
    var tableFields = document.getElementById("readroot");

    tableFields = tableFields.children;
    console.log(tableFields);
    for (item in tableFields) {

        if (isEven(counter)) {
            var tableRow = table.insertRow(-1);
            var label = tableRow.insertCell(-1);
            console.log(tableFields[item]);
            label.appendChild(tableFields[item]);

        } else {
            var field = tableRow.insertCell(-1);
            field.innerHTML = item.innerHTML;


        }

        counter++;
    }

    console.log();
var insertHere = document.getElementById("writeroot");
}

window.onload = function(){
    document.getElementById(\'moreLabor\').onclick = function(){ moreLabor(); }
    moreLabor();
}


</script>

<div id="readroot" style="display: none">
<tr>
    <td><label for="hours">Hours:</label></td>
    <td><input type="text" name="hours[]" value="" /></td>
</tr>
<tr>
    <td><label for="rate">Rate:</label></td>
    <td><input type="text" name="rate[]" value="25" /></td>
</tr>
<tr>
    <td><label for="description">Description:</label></td>
    <td><input type="text" name="description[]" value="" /></td>
</tr>

<input type="hidden" name="invoice_number" value="'.$this->number.'" />
<tr>
    <td><input type="button" value="Remove"
    onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /></td>
</tr>

</div>

<form method="POST" class="invoice" id="edit">
<table id="editTable">
    <tr>
        <td><label>Work Order Number:</label></td>
        <td><input type="text" name="number" value="'.$this->number.'"/></td>
    </tr>
    <tr>
        <td><label>Customer:</label></td>
        <td><select name="customerid">'.$select.'</select></td>
    </tr>
    <span id="writeroot"></span>

    <tr>
        <td><input type="button" id="moreLabor" value="Add labor"/></td>
        <td><input type="submit" name="Save" value="Save" /></td>
    </tr>';
    if (!is_null($this->id)) {
        $form .= '<input type="hidden" name="id" value="'.$this->id.'"/>';
    }
    $form .= '</table></form>';



    $this->component($form);

回答by maerics

The trick is that the DOM Element.childrenattributeis not an array but an array-like collectionwhich has length and can be indexed like an array, but it is not an array:

诀窍是DOMElement.children属性不是数组,而是具有长度并且可以像数组一样索引的类数组集合,但它不是数组:

var children = tableFields.children;
for (var i = 0; i < children.length; i++) {
  var tableChild = children[i];
  // Do stuff
}

Incidentally, in general it is a better practice to iterate over an array using a basic for-loop instead of a for-in-loop.

顺便说一下,一般来说,使用基本的 for 循环而不是 for 循环来迭代数组是更好的做法。

回答by Dat Nguyen

In ECS6, one may use Array.from():

ECS6 中,可以使用Array.from()

const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});

回答by Behnam Esmaili

if tableFieldsis an array , you can loop through elements as following :

如果tableFields是一个数组,你可以循环遍历元素如下:

for (item in tableFields); {
     console.log(tableFields[item]);
}

by the way i saw a logical error in you'r code.just remove ;from end of for loop

顺便说一下,我在你的代码中看到了一个逻辑错误。只需;从 for 循环的末尾删除

right here :

就在这儿 :

for (item in tableFields); {.

for (item in tableFields); {.

this will cause you'r loop to do just nothing.and the following line will be executed only once :

这将导致你的循环什么都不做。以下行将只执行一次:

// Do stuff

回答by code monkey

The backwards compatible version (IE9+) is

向后兼容版本 (IE9+) 是

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

es6的方式是

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});