我们知道 Array.sort()默认按照字母排序,我写了如下代码(代码来自权威指南一书):<ul id="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>four</li>
</ul>
<button id="start" onclick="seachSort('list')" value="确定">确定</button>JS: function seachSort(u) {
if (typeof u == "string") e = document.getElementById(u);
var kids = [];
for (var m = e.firstChild; m != null; m = m.nextSibling) {
if (m.nodeType == 1) kids.push(m);
}
kids.sort(function(a, b) {
var s = a.firstChild.data; var t = b.firstChild.data);
if (s < t) { return -1; }
else if (s > t) { return 1; }
else { return 0; }
});
for (var i = 0; i < kids.length; i++) {
e.appendChild(kids[i]);
}
}点击确定 页面显示:
One
Three
Two
four 理想效果:
four
one
three
two我尝试alert("p">"h"); 好像按照字母表,h应该在p前面吧!!!为什么还会是true?
是我错了,还是作者错了...
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>four</li>
</ul>
<button id="start" onclick="seachSort('list')" value="确定">确定</button>JS: function seachSort(u) {
if (typeof u == "string") e = document.getElementById(u);
var kids = [];
for (var m = e.firstChild; m != null; m = m.nextSibling) {
if (m.nodeType == 1) kids.push(m);
}
kids.sort(function(a, b) {
var s = a.firstChild.data; var t = b.firstChild.data);
if (s < t) { return -1; }
else if (s > t) { return 1; }
else { return 0; }
});
for (var i = 0; i < kids.length; i++) {
e.appendChild(kids[i]);
}
}点击确定 页面显示:
One
Three
Two
four 理想效果:
four
one
three
two我尝试alert("p">"h"); 好像按照字母表,h应该在p前面吧!!!为什么还会是true?
是我错了,还是作者错了...
h是104所以p>h,返回true
sort()应该不是吧只有在字符串比较的时候,才是~·
是先提取第一个char然后对比unicode编码
如果相同再提取第二个char
如果全部相同则保留原来的顺序