Все*_*дно 3 javascript string for-loop
var hello = 'hello';
Array.prototype.unshift.call(hello, '11') // gives error
Array.prototype.join.call(hello, ', ') // works, why??
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释为什么.join有效,为什么.unshift无效
因为字符串是不可变的,并unshift尝试分配给字符串的索引(属性),如
"hello"[4] = '1'
Run Code Online (Sandbox Code Playgroud)
参考:http : //www.ecma-international.org/ecma-262/6.0/#sec-string-exotic-objects:
String 对象是一个奇异的对象,它封装了一个 String 值并公开了对应于 String 值的各个代码单元元素的虚拟整数索引数据属性。Exotic String 对象总是有一个名为“length”的数据属性,其值是封装的 String 值中代码单元元素的数量。代码单元数据属性和“长度”属性都是不可写和不可配置的。
join不分配任何东西,只读取属性,因此它适用于任何具有.length.
| 归档时间: |
|
| 查看次数: |
5208 次 |
| 最近记录: |