Array方面Js底层代码学习记录

一、.clear() →Array

function clear() {
            this.length = 0;
            return this;
        }

  返回清除item的空数组。

  例子:

var fruits = ['Apple', 'Orange', 'Bananas', 'peach'];
fruits.clear();
// -> []
fruits
// -> []

  

二、.clone() →Array

  function clone() {
    return slice.call(this, 0);
  }

  返回数组的副本,保持原始数组不变。

三、.compact() →Array

  function compact() {
    return this.select(function(value) {
      return value != null;
    });
  }

  返回一个副本,不包含null和undefined

  例子:

var orig = [undefined, 'A', undefined, 'B', null, 'C'];
var copy = orig.compact();
// orig -> [undefined, 'A', undefined, 'B', null, 'C'];
// copy -> ['A', 'B', 'C'];

  四、Every([iterator = Prototype.K[, context]]) → Boolean

  • iterator Function - 一个可选函数,用于评估枚举中的每个元素; 该函数应该返回值来测试。如果没有提供,则测试元素本身。
  • context Object - this在对迭代器的调用中使用的可选对象

  确定是否所有元素都是真实的(boolean-equivalent true),直接或通过提供的迭代器计算。(这一块我还不能很好理解)

 function every(iterator) {
    if (this == null) throw new TypeError();
    iterator = iterator || Prototype.K;
    var context = arguments[1];
    var object = Object(this);
    for (var i = 0, length = object.length >>> 0; i < length; i++) {
      if (i in object && !iterator.call(context, object[i], i, object)) {
        return false;
      }
    }
    return true;
  }
  if (arrayProto.every) {
    every = wrapNative(Array.prototype.every);
  }

  五、.filter(iterator[, context]) →Array

  • iterator Function - 用于测试元素的迭代器函数。
  • context Object - this在对迭代器的调用中使用的可选对象

  返回包含此数组中所有项目的新数组,其中 iterator返回了一个真值。

 function filter(iterator) {
    if (this == null || !Object.isFunction(iterator))
      throw new TypeError();

    var object = Object(this);
    var results = [], context = arguments[1], value;

    for (var i = 0, length = object.length >>> 0; i < length; i++) {
      if (i in object) {
        value = object[i];
        if (iterator.call(context, value, i, object)) {
          results.push(value);
        }
      }
    }
    return results;
  }

  if (arrayProto.filter) {
    // `Array#filter` requires an iterator by nature, so we don't need to
    // wrap it.
    filter = Array.prototype.filter;
  }

  六、.first()

  function first() {
    return this[0];
  }

  返回数组的第一个项目(例如,array[0])。

  七、.flatten()  →Array

function flatten() {
    return this.inject([], function(array, value) {
      if (Object.isArray(value))
        return array.concat(value.flatten());
      array.push(value);
      return array;
    });
  }

  个人理解:合并指定数组内的所有数组。

  官方理解:

  返回数组的平坦(一维)副本,保持原始数组不变。嵌套数组以递归方式内联注入。

  常用在处理递归收集算法的结果。

  例子:

var a = [ ' frank ',[ ' bob ',' lisa ' ],[ ' jill ',[ ' tom ',' sally ' ]]];
var b = a.flatten();
// a  - > ['frank',['bob','lisa'],['jill',['tom','sally']]] 
// b  - > ['frank','bob', 'lisa','jill','tom','sally']

  八、.indexOf(item[, offser = 0]) →Number

 function indexOf(item, i) {
    if (this == null) throw new TypeError();

    var array = Object(this), length = array.length >>> 0;
    if (length === 0) return -1;

    // The rules for the `fromIndex` argument are tricky. Let's follow the
    // spec line-by-line.
    i = Number(i);
    if (isNaN(i)) {
      i = 0;
    } else if (i !== 0 && isFinite(i)) {
      // Equivalent to ES5's `ToInteger` operation.
      i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i));
    }

    // If the search index is greater than the length of the array,
    // return -1.
    if (i > length) return -1;

    // If the search index is negative, take its absolute value, subtract it
    // from the length, and make that the new search index. If it's still
    // negative, make it 0.
    var k = i >= 0 ? i : Math.max(length - Math.abs(i), 0);
    for (; k < length; k++)
      if (k in array && array[k] === item) return k;
    return -1;
  }

  官方理解:

  • item? - 可能存在或不存在于数组中的值。
  • offsetNumber - 开始搜索前要跳过的初始项目数。

 返回item数组中第一次出现的索引,或者-1如果item不存在于数组中。Array#indexOf使用绝对等于(===)比较项目。

  个人理解:返回item在数组中首次出现的位置的索引,因为区分了使用了绝对等于所以区分大小写,类型。

  例子:

[3, 5, 6, 1, 20].indexOf(1)
// -> 3
 [3, 5, 6, 1, 20].indexOf(90)
// -> -1 (not found)
 ['1', '2', '3'].indexOf(1);
// -> -1 (not found, 1 !== '1')

  加一个不是Array的例子:

var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")
document.write(str.indexOf("world"))
// ->0
// ->-1
// ->6

  九、.inspect() →String

function inspect() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }

  返回数组的面向调试的字符串表示形式。

  例子:

['Apples', {good: 'yes', bad: 'no'}, 3, 34].inspect()
// -> "['Apples', [object Object], 3, 34]"

  十、.intersect(array) →Array

  function intersect(array) {
    return this.uniq().findAll(function(item) {
      return array.indexOf(item) !== -1;
    });
  }

  返回包含在两个给定数组之间相同的每个项目的数组。

  十一、.last() →

  function last() {
    return this[this.length - 1];
  }

  返回数组的第一个项目(例如,array[array.lenth-1])。

   十二、.lastIndexOf(item[, offset])  →Number

  • item ? - 可能存在或不存在于数组中的值。
  • offset Number - 开始搜索前在结尾跳过的项目数。

  返回最后一次出现的位置item在阵列中-或者-1,如果item没有在数组中存在。

  function lastIndexOf(item, i) {
    if (this == null) throw new TypeError();

    var array = Object(this), length = array.length >>> 0;
    if (length === 0) return -1;

   
    if (!Object.isUndefined(i)) {
      i = Number(i);
      if (isNaN(i)) {
        i = 0;
      } else if (i !== 0 && isFinite(i)) {
        // Equivalent to ES5's `ToInteger` operation.
        i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i));
      }
    } else {
      i = length;
    }

    //如果fromIndex为正值,则将其限制为数组中的最后一个索引;
    //如果它是负数,则从数组长度中减去其绝对值。
    var k = i >= 0 ? Math.min(i, length - 1) :
     length - Math.abs(i);

    //如果他依然是负数,则它将完全绕过这个循环返回-1
    for (; k >= 0; k--)
      if (k in array && array[k] === item) return k;
    return -1;
  }

  十三、.map([iterator = Prototype.K[, context]])  →Array

  • iterator Function - 要应用于枚举中每个元素的迭代器函数。
  • context Object - this在对迭代器的调用中使用的可选对象

  返回应用于iterator数组中每个项目的结果如果没有提供迭代器,则将这些元素简单地复制到返回的数组中。

 
  function map(iterator) {
    if (this == null) throw new TypeError();
    iterator = iterator || Prototype.K;

    var object = Object(this);
    var results = [], context = arguments[1], n = 0;

    for (var i = 0, length = object.length >>> 0; i < length; i++) {
      if (i in object) {
        results[n] = iterator.call(context, object[i], i, object);
      }
      n++;
    }
    results.length = n;
    return results;
  }

  if (arrayProto.map) {
    map = wrapNative(Array.prototype.map);
  }

  十四、reverse([inline = true])  →Array

  • inline Boolean - 是否修改数组。默认为true克隆原始数组时false
 function reverse(inline) {
    return (inline === false ? this.toArray() : this)._reverse();
  }

  例子:

         // Making a copy
         var nums = [3, 5, 6, 1, 20];
         var rev = nums.reverse(false);
         // nums -> [3, 5, 6, 1, 20]
         // rev -> [20, 1, 6, 5, 3]
   
         // Working inline
         var nums = [3, 5, 6, 1, 20];
         nums.reverse();
         // nums -> [20, 1, 6, 5, 3]

   十五、.Size()   →Number 

  function size() {
    return this.length;
  }

  返回数组的长度

  十六、toArray() → Array

  function clone() {
    return slice.call(this, 0);
  }

  别名 .clone()

  十七、.uniq()

  function uniq(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  }
  • sorted Boolean - 数组是否已被排序。如果true使用成本较低的算法。

  生成一个数组的重复版本。如果没有找到重复项,则返回原始数组。

  在大型阵列时sortedfalse,这种方法有一个潜在很大的性能代价。

  例子:

     [1, 3, 2, 1].uniq();
// -> [1, 2, 3]
['A', 'a'].uniq();
// -> ['A', 'a'] (because String comparison is case-sensitive)

  十八、.without(value[, value...])   → Array

  function without() {
    var values = slice.call(arguments, 0);
    return this.select(function(value) {
      return !values.include(value);
    });
  }
  • value ? - 要排除的值。

生成不包含任何指定值的数组的新版本,保持原始数组不变。

  例子:

[3, 5, 6].without(3)
// -> [5, 6]
[3, 5, 6, 20].without(20, 6)
// -> [3, 5]
原文地址:https://www.cnblogs.com/xuxml/p/8466011.html