简体   繁体   English

javascript中字符串的数组取消移位

[英]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有人可以向我解释为什么.join有效,为什么.unshift无效

Because strings are immutable, and unshift tries to assign to an index (property) of the string, as in因为字符串是不可变的,并且unshift尝试分配给字符串的索引(属性),如

"hello"[4] = '1'

Reference: http://www.ecma-international.org/ecma-262/6.0/#sec-string-exotic-objects :参考: 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. String 对象是一个奇异的对象,它封装了一个 String 值并公开了对应于 String 值的各个代码单元元素的虚拟整数索引数据属性。 Exotic String objects always have a data property named "length" whose value is the number of code unit elements in the encapsulated String value. Exotic String 对象总是有一个名为“length”的数据属性,其值是封装的 String 值中代码单元元素的数量。 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 . join不分配任何东西,只读取属性,因此它适用于任何具有.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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