Skip to content

Instantly share code, notes, and snippets.

@LuoZijun
Last active April 10, 2019 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LuoZijun/16d532fdf595b135bd9caa12ed96c29a to your computer and use it in GitHub Desktop.
Save LuoZijun/16d532fdf595b135bd9caa12ed96c29a to your computer and use it in GitHub Desktop.
JS 大数组排序问题
页面

https://dev.w3.org/html5/html-author/charref

使用火狐或者谷歌浏览器打开上面这个页面,然后打开控制台,输入以下 ECMAScript 代码,运行后,发现排序结果并不对 ...

更新:查阅 Array.prototype.sort 文档后,发现这是 JS 会把数组里面的元素自动转换成字符串,然后毕竟字符串的 CodePoint 导致的(如果 sort 函数没有传递 比较函数的话)。

let dom = document.getElementsByTagName('table')[0].tBodies[0];

let table = Array.prototype.map.call(dom.children, function(tr){
    return Array.prototype.reduce.call(tr.children, function (acc, td){
        let name = td.className;
        let value = td.textContent;

        if ( name === 'character' ) {
            if ( value.length > 1 && value[0] === ' ' ) {
                value = value.slice(1);
            }
            acc[name] = value;
        } else if ( name === 'named' ) {
            acc[name] = value.split(" ");
        } else if ( name === 'hex' ) {
            acc[name] = value;
        } else if ( name === 'dec' ) {
            acc[name] = value;
        } else if ( name === 'desc' ) {
            acc[name] = value;
        } else {
            throw new Error('Ooops ...');
        }

        return acc;
    }, {})
});

let codes = table.map(function (item){
    let code_point = Number(item['dec'].replace("&#", "").replace(";", ""));
    return code_point
});

// 手动查看后,发现排序结果并不对 -_-
codes.sort();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment