繁体   English   中英

字符串上的Array.sort

[英]Array.sort on a string

有谁知道为什么在字符串上调用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("");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM