# Javascript数组方法探究一二

1. Array.prototype.slice方法

1 var nodesArr = Array.prototype.slice.call(document.forms);
2
3 var argsArr = Array.prototype.slice.call(arguments);

 1 function ArraySlice(start, end) {
2   CHECK_OBJECT_COERCIBLE(this, "Array.prototype.slice");
3   ...
4   var result = []; // 这句是关键
5
6   if (end_i < start_i) return result;
7
8   if (UseSparseVariant(array, len, IS_ARRAY(array), end_i - start_i)) {
9      ...
10     SparseSlice(array, start_i, end_i - start_i, len, result);
11   } else {
12     SimpleSlice(array, start_i, end_i - start_i, len, result);
13   }
14   ...
15   return result;

 var nodesArr = Array.prototype.splice.call(document.forms, 0);

1 var arr = [1, 2, 3];
2 var cloneArr = arr.slice(); // cloneArr:  [1, 2, 3]

(1). [].concat.apply([], 类数组);
(2). var arr = [];   [].push.apply(arr, 类数组);

2. Array.prototype.push 方法

1 var arr1 = [1, 'str', {name: 'lang'}];
2 var arr2 = [2, 'ing'];
3 Array.prototype.push.apply(arr1, arr2);
4 // 返回结果：[1, "str", {name: 'lang'}, 2, "ing"]

3. Array.prototype.sort 方法

var arr = ['1', '2', '10', '12'];
arr.sort();
// 返回结果：["1", "10", "12", "2"]

arr.sort(function(a, b) {
return a - b;
})
// 返回结果：["1", "2", "10", "12"]

4. length 属性

1 var arr = [1, 2, 3, 4];
2 arr.length = 2;
3 // arr: [1, 2]
4 arr.length = 0;
5 // arr: []

1 var arr = [];
2 arr.length = 3;
3 // arr: [undefined, undefined, undefined]

posted @ 2015-01-08 00:27  阿郎博客  阅读(1213)  评论(6编辑  收藏