繁体   English   中英

Array.prototype.join.call 在后台对字符串做了什么?

[英]What does Array.prototype.join.call do in the background for a string?

var a = "foo";
var c = Array.prototype.join.call( a, "-" ); // 'f-o-o'

第二行代码是如何工作的? 我没有看到将字符串转换为数组然后再次转换回来,这是在后台发生的吗? 我遇到过这种代码,很奇怪,一个接受字符串的数组方法。

请参阅Array.prototype.join的规范(如下) 它不要求它操作的this是一个数组,只需要它有一个length和名称,如01等。 字符串可以,因此join可以处理字符串。

从规范:

注 2: join函数是有意通用的; 它不要求它的this值是一个Array对象。 因此,它可以转移到其他种类的对象中作为方法使用。

这是规范中的完整算法:

  1. be ToObject ( this value).ToObject值)。
  2. ). ReturnIfAbrupt ( )。
  3. be ToLength ( Get ( , "length" )).ToLength ( Get ( , "length" ))。
  4. ). ReturnIfAbrupt ( )。
  5. is undefined , let be the single-element String "," .如果未定义,则让为单元素字符串","
  6. be ToString ( ).ToString)。
  7. ). ReturnIfAbrupt ( )。
  8. is zero, return the empty String.如果为零,则返回空字符串。
  9. be Get ( , "0" ).Get ( , "0" )。
  10. is undefined or null , let be the empty String;如果undefinednull ,则令为空字符串; be ToString ( ).否则,令ToString ( )。
  11. ). ReturnIfAbrupt ( )。
  12. be 1 .1
  13. < 重复,而 <
    1. be the String value produced by concatenating and .是通过连接产生的字符串值。
    2. be Get ( , ToString ( )).Get ( , ToString ( ))。
    3. is undefined or null , let be the empty String;如果undefinednull ,则让为空字符串; be ToString ( ).否则,让成为ToString ( )。
    4. ). ReturnIfAbrupt ()。
    5. be a String value produced by concatenating and .是通过连接产生的 String 值。
    6. by 1.增加 1。
  14. .返回

字符串是类似数组的对象,因为它具有属性length ,并且您可以使用[]访问其元素(字符),因为您可以对其应用大多数数组操作操作。

Function.prototype.call()调用给定函数的函数,使用第一个参数作为this并使用流参数作为普通参数。

作为那个Array.prototype.join.call(a, "-")将在你的情况下调用对象a上的函数join字符串。

字符串是类数组对象。 类数组对象提供对元素和属性长度的索引访问。 你可以在这里阅读更多

暂无
暂无

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

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