JavaScript基础篇(3)之Object、Function等引用类型(2)

var arr2 = [5, 14, 23, 12, 1, 123, 23, 4, 5, 6, 32, 5, 3, 2, 1]; arr2.mysort = function (fun) { //*********************具体排序过程******************* for (var i = 0; i < arr2.length - 1; i++) { for (var j = 0; j < arr2.length - i; j++) { if (fun(arr2[j], arr2[j + 1]) > 0) {//这里用我们传进来的方法判断是否要排序调换位置 var temp = arr2[j]; arr2[j] = arr2[j + 1]; arr2[j + 1] = temp; } } } //*************************************************** return arr2; } function mycompare(o1, o2) { return o1 - o2;//回调函数(具体的比较规则) } alert(arr2.mysort(mycompare)); var arr2 = [5, 14, 23, 12, 1, 123, 23, 4, 5, 6, 32, 5, 3, 2, 1]; arr2.mysort = function (fun) { //*********************具体排序过程******************* for (var i = 0; i < arr2.length - 1; i++) { for (var j = 0; j < arr2.length - i; j++) { if (fun(arr2[j], arr2[j + 1]) > 0) {//这里用我们传进来的方法判断是否要排序调换位置 var temp = arr2[j]; arr2[j] = arr2[j + 1]; arr2[j + 1] = temp; } } } //*************************************************** return arr2; } function mycompare(o1, o2) { return o1 - o2;//回调函数(具体的比较规则) } alert(arr2.mysort(mycompare));

当然,我们模拟的并不是那么的好,大概就是这么个意思。

反序就简单了:(直接reverse()就可以了)

function mysort(o1, o2) { return o1 - o2;//如果为正数则o1大,负数则o2大,零则相等。 } var arr2 = [5, 14, 23, 12, 1]; arr2.sort(mysort); arr2.reverse(); alert(arr2);

数组的一些操作方法:
concat创建一个新的副本,并合并传进来的参数

var colors = ["red", "green", "blue"]; var colors2 = colors.concat("yellow", ["black", "brown"]); alert(colors); //red,green,blue alert(colors2); //red,green,blue,yellow,black,brow

slice创建一个新的副本,取数组的位置数据

var colors = ["red", "green", "blue", "yellow", "purple"]; var colors2 = colors.slice(1);//从下标为1的开始,到末尾 var colors3 = colors.slice(1, 4);//从下标1(包含1)到4(不包含4) alert(colors2); //green,blue,yellow,purple alert(colors3); //green,blue,yellow

splice会改变原数组数据,可实现对数组的删、插和替换

var colors = ["red", "green", "blue"]; var removed = colors.splice(0, 1); // 删除第一项(从下标0开始,删除1项) alert(colors); // green,blue alert(removed); // red,返回的数组中只包含一项 removed = colors.splice(1, 0, "yellow", "orange"); // 从位置 1 开始插入两项(从下标0开始,删除0项,并插入后面的参数数据) alert(colors); // green,yellow,orange,blue alert(removed); // 返回的是一个空数组 removed = colors.splice(1, 1, "red", "purple"); // 插入两项,删除一项(从下标1开始,删除1项[也就是yellow],并插入后面的参数数据) alert(colors); // green,red,purple,orange,blue alert(removed); // yellow,返回的数组中只包含一项

查找位置方法

indexOf()和 lastIndexOf(),就是查找在数组中的位置,和string中的对应方法差不多。

迭代方法

 every():对数组中的每一项运行给定函数,如果该函数对每一项都返回 true,则返回 true。
 filter():对数组中的每一项运行给定函数,返回该函数会返回 true 的项组成的数组。
 forEach():对数组中的每一项运行给定函数。这个方法没有返回值。
 map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
 some():对数组中的每一项运行给定函数,如果该函数对任一项返回 true,则返回 true。

以上方法都不会修改数组中的包含的值。

如:

var numbers = [1,2,3,4,5,4,3,2,1]; var everyResult = numbers.every(function(item, index, array){ return (item > 2); }); alert(everyResult); //false

其中。forEach和map区别不大,只是一个有返回值,一个没有。实际中我们用forEach比较多,下面我们模拟forEach的实现。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgzgdd.html