javascript中数组的方法有哪些?

数组长度

arr.length()  数组的长度

返回或设置一个数组中的元素个数

var arr = [4, 6, 12, 1, 32, 44, 9]
console.log(arr.length);   // 输出为7

数组类型转换

arr.toString()  转为字符串

1.把数组转换为数组值(逗号分隔)的字符串。

var arr = [4, 6, 12, 1, 32, 44, 9]
console.log(arr.toString(","));  //输出为 4,6,12,1,32,44,9

2.arr.join("")  将数组拼接成字符串

将数组拼接成字符串,可将所有数组元素结合为一个字符串。还可以规定分隔符

var arr = [4, 6, 12, 1, 32, 44, 9]
console.log(arr.join("=>"));   //输出为 4=>6=>12=>1=>32=>44=>9

数组的增删改查

1.添加

unshift() 方法从头部添加新元素,并返回数组的长度

push() 方法在数组末位添加一个新的元素:

2.删除

shift() 方法从头部删除数组元素,如果数组为空则返回undefined,并返回数组的长度

pop() 方法从数组末位删除一个元素;

3.查找

indexOf 查找元素索引

findindex()通过id找索引

4.改变数组元素

4.1裁剪数组

slice() 方法用数组的某个片段切出新数组。

slice() 方法创建新数组。它不会从源数组中删除任何元素。

slice() 可接受两个参数,slice(开始参数,结束参数)

4.2合并数组

concat() 方法通过合并(连接)现有数组来创建一个新数组

concat() 方法不会更改现有数组。它总是返回一个新数组。

concat() 方法可以使用任意数量的数组参数:

语法: arr1.concat(arr2, arr3, ..., arrX)

var arr1 = ["李冰冰", "邓紫棋"];
var myChildren = arr1.concat(["zs", "ls", "ww"]); 

console.log(myChildren)

 4.3拼接数组

splice(定义了应添加新元素的位置(拼接),定义应删除多少元素,定义要添加的新元素)

splice(定义新元素应该被添加(接入)的位置,定义应该删除多个元素)

splice() 方法返回一个包含已删除项的数组:

数组排序

翻转数组reverse()

var arr = [4, 6, 12, 1, 32, 44, 9]
console.log(arr.reverse());   //输出为 [9, 44, 32, 1, 12, 6, 4]

数组冒泡排序sort()

var arr = [4, 6, 12, 1, 32, 44, 9]
console.log(arr.sort());   //输出为 [1, 12, 32, 4, 44, 6, 9]  按首字母排序

升序和降序

var arr = [4, 6, 12, 1, 32, 44, 9]
arr.sort(function (a, b) {
    return a - b;   // 升序排序 输出为  [1, 4, 6, 9, 12, 32, 44]
    // return b - a;   降序排序 输出为  [44, 32, 12, 9, 6, 4, 1]
    })
console.log(arr);

数组对象

valueOf() 返回数组对象的原始值

语法: array.indexOf(item,start)

遍历数组

forEach() 数组每个元素都执行一次回调函数

语法:array.forEach(function(currentValue, index, arr), thisValue)

map() 通过指定函数处理数组的每个元素,并返回处理后的数组

语法:array.map(function(currentValue,index,arr), thisValue)

filter()过滤器 检测数值元素,并返回符合条件所有元素的数组。

语法: array.filter(function(currentValue,index,arr), thisValue)
Demo:
showArr() {
            if (this.getSel === "yes") {
                return this.list.filter((obj) => obj.isDone === true);
            } else if (this.getSel === "no") {
                return this.list.filter((obj) => obj.isDone === false);
            } else if (this.getSel === "all") {
                return this.list;
            }
        },

every() 检测数值元素的每个元素是否都符合条件。

语法: array.every(function(currentValue,index,arr), thisValue)

some() 检测数组元素中是否有元素符合指定条件。

语法: array.some(function(currentValue,index,arr),thisValue)

reduce() 将数组元素计算为一个值(从左到右

语法: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

reduceRight() 将数组元素计算为一个值(从右到左)

语法: array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值