javascript - Array.sort on a string - Stack Overflow

Does anyone know why it's illegal to call Array.sort on a string?[].sort.call("some string&qu

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("");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742336469a4424748.html

相关推荐

  • javascript - Array.sort on a string - Stack Overflow

    Does anyone know why it's illegal to call Array.sort on a string?[].sort.call("some string&qu

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信