Array.sort on line

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

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

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

 [].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"] 
+4
source share
2 answers

Lines are immutable. You cannot change the line; in particular, Array.prototype.sort will change the string to sort, so you cannot do this. You can only create a new, different line.

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

Because strings are immutable.

The functions you mention work, return a new object, they do not update the line in place.

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

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

Source: https://habr.com/ru/post/1493991/


All Articles