As far as I understood, some Array methods can be used on strings by using the call method. While coming up with an answer for this question:
I came across an issue I wasn't expecting. I couldn't use pop.apply()
on a string without receiving this error;
"message": "Uncaught TypeError: Cannot delete property '39' of [object String]"
Why did this fail and why do only some array methods work?
let href = $('.anchor').prop('href');
Array.prototype.pop.call(href);
console.log(href);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/my-account/#example/" class="anchor">...</a>
Not all array methods can be used on array. Those methods which try to mutate the string won't work. In Javascript strings are immutable. So methods like push
, pop
, shift
, splice
don't work.