Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I `.call` Array.prototype.splice on a string?

I understand I could and probably should use substring :)

For educational reasons, I want to know why I can't use call to do a splice operation on a string, which I understand to be an array-like object. It seems like this should work:

Array.prototype.splice.call('filename.jpg', -3, 3).join(''); // return the last three chars

Throws error TypeError: Object.isSealed called on non-object in V8.

like image 820
SimplGy Avatar asked Jul 01 '26 08:07

SimplGy


2 Answers

In Javascript, strings are immutable; they can't be changed after they're created. So there's no "set char" or "splice" methods because a string can't be changed. You can, however, call split('') on them to turn them into arrays, so you can use 'filename.jpg'.split('').splice(-3, 3).join('') for the same effect.

You need to convert it to an array object first

Array.prototype.splice.call('filename.jpg'.split(''), -3, 3).join('');
like image 41
14 revs, 12 users 16% Avatar answered Jul 02 '26 23:07

14 revs, 12 users 16%