简体   繁体   中英

Array unshift for string in javascript

var hello = 'hello';
Array.prototype.unshift.call(hello, '11') // gives error
Array.prototype.join.call(hello, ', ') // works, why??

can someone explain to me why .join works and why .unshift doesn't

Because strings are immutable, and unshift tries to assign to an index (property) of the string, as in

"hello"[4] = '1'

Reference: http://www.ecma-international.org/ecma-262/6.0/#sec-string-exotic-objects :

A String object is an exotic object that encapsulates a String value and exposes virtual integer indexed data properties corresponding to the individual code unit elements of the String value. Exotic String objects always have a data property named "length" whose value is the number of code unit elements in the encapsulated String value. Both the code unit data properties and the "length" property are non-writable and non-configurable.

join doesn't assign anything and only reads properties, therefore it works with any object that has .length .

Try this:

 String.prototype.unshift = function(el) { let arr = [this]; arr.unshift(el); return arr.join(""); } var s = "BCD"; s = s.unshift("A"); console.log(s); // ABCD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM