Discuss / JavaScript / 交作业

交作业

Topic source
// sort list:
let thatOl = document.getElementById('test-list');
[].slice.call(thatOl.querySelectorAll('li')).sort(function(x, y){
    return x.innerText > y.innerText;
}).forEach(function(item){
    thatOl.appendChild(item);
});

拉了一泡屎回来,发现应该可以省略一次遍历,下面是改进版:

// sort list:
let thatOl = document.getElementById('test-list');
[].slice.call(thatOl.querySelectorAll('li')).sort(function(x, y){
    x.innerText > y.innerText && (thatOl.insertBefore(y, x));
});

改进版有bug,请无视。。。

Gods_巨蚁

#4 Created at ... [Delete] [Delete and Lock User]

// sort list: var langList = document.getElementById('test-list'); var langs = document.getElementsByClassName('lang'); var i; var arr = []; for (i = 0; i < langs.length; i++) { arr.push(langs[i]); } arr .sort(function(x, y) { var s1 = x.innerText; var s2 = y.innerText; if (s1 < s2) { return -1; } else if(s1 > s2) { return 1; } else { return 0; } });

for (i = 0; i < arr.length; i++) { langList.appendChild(arr[i]); }


  • 1

Reply