有誰知道爲什麼在一個字符串上調用Array.sort是非法的嗎?Array.sort在字符串
[].sort.call("some string")
// "illegal access"
但調用Array.map,Array.reduce或Array.filter是好嗎?
[].map.call("some string", function(x){
return String.fromCharCode(x.charCodeAt(0)+1);
});
// ["t", "p", "n", "f", "!", "t", "u", "s", "j", "o", "h"]
[].reduce.call("some string", function(a, b){
return (+a === a ? a : a.charCodeAt(0)) + b.charCodeAt(0);
})
// 1131
[].filter.call("some string", function(x){
return x.charCodeAt(0) > 110;
})
// ["s", "o", "s", "t", "r"]
有道理!我一直在使用split - > sort - > join,但只是想爲代碼高爾夫尋找一個更短的方法 – nderscore