对字符串进行数组排序

Array.sort on a string

本文关键字:数组排序 字符串      更新时间:2023-09-26

有人知道为什么在字符串上调用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"]
字符串是不可变的。你实际上无法更改字符串;特别是,Array.prototype.sort会修改要排序的字符串,所以您不能这样做。您只能创建一个新的、不同的字符串。
x = 'dcba';
// Create a character array from the string, sort that, then
// stick it back together.
y = x.split('').sort().join('');
因为字符串是不可变的。

你提到的工作函数返回一个新对象,它们不会更新字符串。

当然,不那么直接地对字符串进行排序很容易:

var sorted = "some string".split("").sort().join("");