为了账号安全,请及时绑定邮箱和手机立即绑定

JavaScript数组方法总结(中)

JavaScript中提供了多种数组方法,如下:

  1. 转换方法—toLocaleString()方法、toString()方法、valueOf()方法
  2. 栈方法——push()方法、pop()方法
  3. 队列方法——shift()方法、unshift()方法
  4. 重排序方法——reverse()方法、sort()方法
  5. 操作方法——concat()方法、slice()方法、splice()方法
  6. 位置方法——indexOf()方法、lastIndexOf()方法
  7. 迭代方法——every()方法、filter()方法、forEach()方法、map()方法、some()方法
  8. 归并方法——reduce()方法、reduceRight()方法
    重排序方法:

①:reverse()方法可以反转数组项的顺序
②:sort()方法对数组进行升序排序,但sort()方法会调用每个数组项的toString()转型方法,所以sort()方法比较的是字符串,所以为了能正确排序,要将一个排序函数作为参数传给sort()方法。
具体例子如下:

//reverse()方法
var values=[0,1,5,10,15];
values.reverse();
console.log(values);    //15,10,5,1,0

//无参数sort()方法
values.sort();
console.log(values);    //0,1,10,15,5

//将比较函数作为参数传给sort()方法
//此比较函数用于数值类型或者其valueOf()方法会返回数值类型的对象类型
function compare(value1,value2){
    return value1-value2;    //升序,若要降序则return value2-value1;
}
values.sort(compare);
console.log(values);    //0,1,5,10,15

//使用另外一种比较函数一样可以解决,并适用于大多数数据类型
function compare2(value1,value2){
    if(value1<value2){
        return -1;
    }
    else if(value1>value2){
        return 1;
    }
    else{
        return 0;
    }
}
values.sort(compare2);
console.log(values);    //0,1,5,10,15
//用字符串数据类型检验
var colors=["red","blue","green","black"];
colors.sort(compare2);
console.log(colors);    //black,blue,green,red

colors.sort(compare);
cosole.log(colors);    //返回原函数,不进行排序

操作方法:

①:concat()方法用于连接两个或多个数组,不改变现有数组,只是返回被连接数组的一个副本
②:slice()方法能基于当前数组中的一个或多个项创建一个数组,接受一个或两个参数,即返回项的开始跟结束位置
③:splice()方法,(返回数组)使用这种方法的方式有三种,如下:

若要删除的项数为0,则返回空数组;若不为0,则返回由被移除项所组成的数组

  • 删除:可以删除任意数量的项,只需指定两个参数,要删除的第一项和要删除的项数
  • 插入:可以向指定位置插入任意数量的项:只需指定三个参数,起始位置、0(要删除的项数)、要插入的项
  • 替换:可以向指定位置插入任意数量的项,且同时删除任意数量的项,只需指定三个参数,起始位置、要删除的项数和要插入的任意数量的项

具体例子如下:

//删除
var colors=["red","green","blue"];
var removed=colors.splice(0,1);    //删除colors数组0的位置的项
console.log(colors);    //green,blue
console.log(removed);    //red,返回数组只包含一项

//插入
removed=colors.splice(1,0,"yellow","orange");    //从colors数组1的位置插入两项
console.log(colors);    //green,yellow,orange,blue
cosole.log(removed);    //因为删除项数为0,所以返回空数组

//替换
removed=colors.splice(1,1,"red","purple");    //删除colors数组1的位置的项,并在此插入两项
console.log(colors);    //green,red,purple,orange,blue
console.log(removed);    //yellow,返回数组只包含一项
点击查看更多内容
5人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消