字符串上的Array.sort

nde*_*ore 4 javascript

有谁知道为什么在字符串上调用Array.sort是违法的?

[].sort.call("some string")
// "illegal access"
Run Code Online (Sandbox Code Playgroud)

但是调用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"]
Run Code Online (Sandbox Code Playgroud)

use*_*ica 6

字符串是不可变的.你实际上不能改变一个字符串; 特别是,Array.prototype.sort会修改要排序的字符串,因此您不能这样做.您只能创建一个新的不同字符串.

x = 'dcba';
// Create a character array from the string, sort that, then
// stick it back together.
y = x.split('').sort().join('');
Run Code Online (Sandbox Code Playgroud)