为什么String表现得像Array?-JS

Ama*_*ngh 1 javascript arrays string types

大家都知道它的Strings行为有点像Array。您甚至可以对其应用一些数组方法并从中受益,例如以下示例。

[].filter.call('abcdef',function(val){
    return val<'e';
});
Run Code Online (Sandbox Code Playgroud)

也,

var a='xyz';
Run Code Online (Sandbox Code Playgroud)

我可以使用来访问第一个元素,a[0]也可以a.length像Array

我的问题是,为什么String表现得像个孩子Array。如果是的话,为什么false在检查它是否为的实例时为何会出现以下信息Array。是String Array-like吗

'a' instanceof Array
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

所有这一切Array.prototype.filter真的需要是变量上迭代有一个length属性,该变量的数值,索引值。参见polyfill(的一部分):

var len = this.length >>> 0,
    res = new Array(len), // preallocate array
    t = this, c = 0, i = -1;
if (thisArg === undefined){
  while (++i !== len){
    // checks to see if the key was set
    if (i in this){
      if (func(t[i], i, t)){
        res[c++] = t[i];
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

字符串满足此条件-字符串具有length属性,并且在字符串上访问的数字标记解析为单个字符。

但是您可以对任意对象执行相同的操作:

var len = this.length >>> 0,
    res = new Array(len), // preallocate array
    t = this, c = 0, i = -1;
if (thisArg === undefined){
  while (++i !== len){
    // checks to see if the key was set
    if (i in this){
      if (func(t[i], i, t)){
        res[c++] = t[i];
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以说它也obj很像数组,因为它具有length属性和数字索引。大多数数组方法(例如.filter,.reduce等)都可以.call在类似数组的对象上使用,即使这些对象不是实际的数组也是如此。

(从技术上讲,您也可以在非类似数组的对象上调用数组方法,这只会做任何有用的事情-不能执行任何迭代)