JavaScript 数组对象(部分)
数组的增删改查
var arr=["arr1","arr2","arr3","arr4"];
arr.pop();
var arr=["arr1","arr2","arr3","arr4"];
arr.shift();
- .push(参数1,参数2…): 在尾部添加元素;
(参数为要添加的元素)
var arr=["arr1","arr2","arr3","arr4"];
arr.push("newArr1","newArr2","newArr3");
- unshift(参数1,参数2…):在头部添加元素
(参数为要添加的元素 返回值为新数组长度length)
var arr=["arr1","arr2","arr3","arr4"];
arr.unshift("newArr1","newArr2","newArr3");
- splice(参数1,参数2,参数3…参数x):从数组中添加或者删除元素;
参数1:必需、整数,规定删除/添加元素的从哪个下标开始。 参数2:必需、整数,规定删除/添加的元素个数,若为0 则不删除元素; 参数3-参数x:可选,从参数1开始的位置添加新元素; 返回值为被删除或者添加的元素所组成的数组; 多个参数之间用逗号隔开。
var arr=["arr1","arr2","arr3","arr4"];
arr.splice(2,2);
arr.splice(2,0,"newArr1","newArr2");
- .slice(参数1,参数2):截取数组
参数1:开始截取的下标位置,可以为负数; 参数2:结束截取的位置(不包含参数2),若省略则截取到数组的尾部,可以为负数; 参数1要小于等于参数2(不含负值) 返回值:截取到的数组;
var arr=["arr1","arr2","arr3","arr4"];
arr.slice(1,2);
- .forEach(function(参数1,参数2,参数3){函数体});或者采用箭头函数:.forEach((参数)=>{函数体});
该函数专用来做数组遍历,至少本人是这样的。
var arr=["arr1","arr2","arr3","arr4"];
arr.forEach((item,index,list)=>{
});
- .map(function(参数1,参数2,参数3){ 函数体})或者.map((参数)=>{函数体})
该函数不会对空数组进行检测,不会对数组顺序进行修改; 返回值为数组,返回的新数组跟原数组为一一映射的关系;
var arr=["50","60","70","80"];
arr.map((item,index,list)=>{
});
- .reduce((total,item,index,list)=>{函数体},初始值); 迭代求和
total: 必需 初始值 或者是计算后的初始值; item:遍历的每一个元素; index:元素对应下标; list:数组
var sum = arr.reduce((total,item)=>{
return total+item
});
- .join(参数); 将数组所有的元素放入一个字符串中;
参数:可选 分隔符 比如"-" " 。“等,如不写默认为’ , '逗号; 若为空串,arr.join(”");则没有分隔符; 返回值为拼合后的字符串;
var arr=["arr1","arr2","arr3","arr4"];
var newArr = arr.join("");
- .reverse(); 颠倒数组中元素的顺序;
返回值为颠倒后的新数组
var arr=["arr1","arr2","arr3","arr4"];
var newArr = arr.reverse();
好了,累了,今天就到这了,告辞;
|