最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Array.sort on a string - Stack Overflow

programmeradmin1浏览0评论

Does anyone know why it's illegal to call Array.sort on a string?

[].sort.call("some string")
// "illegal access"

But calling Array.map, Array.reduce, or Array.filter is okay?

[].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"]

Does anyone know why it's illegal to call Array.sort on a string?

[].sort.call("some string")
// "illegal access"

But calling Array.map, Array.reduce, or Array.filter is okay?

[].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"]
Share Improve this question edited Dec 18, 2013 at 4:39 nderscore asked Jul 29, 2013 at 2:08 nderscorenderscore 4,26124 silver badges29 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

Strings are immutable. You can't actually change a string; in particular, Array.prototype.sort would modify a string to be sorted, so you can't do that. You can only create a new, different string.

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

Because strings are immutable.

The functions you mention that work return a new object, they don't update the string in place.

Of course it's easy to sort a string a little less directly:

var sorted = "some string".split("").sort().join("");
发布评论

评论列表(0)

  1. 暂无评论