简体   繁体   English

使用Array的Javascript中的HTML表排序有效,但是为什么呢?

[英]HTML table sort in Javascript with Array works but why?

In this code: 在此代码中:

 let container = document.getElementById('variables'); Array.from(container.querySelectorAll('tr')) .sort((a, b) => a.getAttribute("name").localeCompare(b.getAttribute("name"), )) .forEach(tr => container.appendChild(tr)); 
 <table id="variables"> <tr name=B> <td>B</td> </tr> <tr name=A> <td>A</td> </tr> <tr name=C> <td>C</td> </tr> </table> 

I create an unsorted HTML table and sort it with JavaScript. 我创建一个未排序的HTML表,并使用JavaScript对其进行排序。

I works but I do not understand why I do not get the original array followed by the sort one because the forEach do appendChild to the original table 我的作品,但我不明白为什么我不得到原始数组跟在后面的排序一,因为forEachappendChild到原始表

What is the magic behind this code? 该代码背后的魔力是什么?

foo.appendChild(bar) puts bar at the end of foo . foo.appendChild(bar)bar放在foo的末尾。

Since an element can't exist in two places at the same time, if it was already the child of another element, it is removed from there first. 由于一个元素不能同时存在于两个位置,因此,如果它已经是另一个元素的子元素,则首先将其从那里删除。

ie it is not the same as foo.appendChild(bar.cloneNode(true)) 即它与foo.appendChild(bar.cloneNode(true))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM