📜  Prototype-数组处理

📅  最后修改于: 2020-10-21 08:44:12             🧑  作者: Mango


 

Prototype通过许多强大的方法扩展了所有本机JavaScript数组。

这通过两种方式完成-

  • 它混入了Enumerable模块,该模块已经引入了大量方法。
  • 它添加了很多其他方法,本节将对此进行介绍。

使用迭代器

Prototype提供的一项重要支持是您可以像JavaScript中的迭代器一样使用Java。看到下面的区别-

编写for循环的传统方式-

for (var index = 0; index < myArray.length; ++index) {
   var item = myArray[index];
   // Your code working on item here...
}

现在,如果您正在使用Prototype,则可以按如下所示替换上面的代码-

myArray.each(function(item) {
   // Your code working on item here...
});

这是所有函数的列表,以及涉及Array的示例。

原型数组方法

注意-确保您拥有1.6的prototype.js版本。

S.No. Method & Description
1. clear()

Clears the array (makes it empty).

2. clone()

Returns a duplicate of the array, leaving the original array intact.

3. compact()

Returns a new version of the array, without any null/undefined values.

4. each()

Iterates over the array in ascending numerical index order.

5. first()

Returns the first item in the array, or undefined if the array is empty.

6. flatten()

Returns a “flat” (one-dimensional) version of the array.

7. from()

Clones an existing array or creates a new one from an array-like collection.

8. indexOf()

Returns the position of the first occurrence of the argument within the array.

9. inspect()

Returns the debug-oriented string representation of an array.

10. last()

Returns the last item in the array, or undefined if the array is empty.

11. reduce()

Reduces arrays: one-element arrays are turned into their unique element, while multiple-element arrays are returned untouched.

12. reverse()

Returns the reversed version of the array. By default, directly reverses the original. If inline is set to false, uses a clone of the original array.

13. size()

Returns the size of the array.

14. toArray()

This is just a local optimization of the mixed-in toArray from Enumerable.

15. toJSON()

Returns a JSON string.

16. uniq()

Produces a duplicate-free version of an array. If no duplicates are found, the original array is returned.

17. without()

Produces a new version of the array that does not contain any of the specified values.