Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

javascript - Using Array.prototype.sort.call to sort a HTMLCollection

var down=function(a,b){alert(a)}
Array.prototype.sort.call(table.tBodies[0].childNodes,down)
Array.prototype.sort.call([0,1,2,3],down)

Why do I not get alerts from the first sort call?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Convert the NodeList to an array first:

var elements = [].slice.call(table.tBodies[0].childNodes);

and then call sort normally:

elements.sort(down);

It seems sort cannot handle array-like objects. This is probably because NodeList does not provide any methods to change the list, but sort sorts the array in-place.

Update: For more information, from the specification:

Perform an implementation-dependent sequence of calls to the [[Get]] , [[Put]], and [[Delete]] internal methods of obj.

I assume NodeLists don't have these internal methods. But this is really just an assumption. It could also be that this is implementation dependent.

I also suggest you use .children [MDN] instead of .childNodes to only get element nodes. Update: Or .rows [DOM Spec] as @patrick suggests.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...