js数组容器中包含的属性和方法概述
更新:HHH   时间:2023-1-7


1、.length----获取数组长度;

var arr = [1,2,3,4,5];
console.log(arr.length)  //5

2、shift()----删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined,直接在元数组上修改;

var arr= [1,2,3,4,5];
var result = arr.shift(); 
console.log(arr)   //[2,3,4,5]
console.log(result)   //1

3、unshift()----将参数添加到原数组开头,并返回数组的长度,直接在元数组上修改;

arr = [1,2,3,4,5];
result = arr.unshift(-2,-1);
console.log(arr)   //[-2,-1,1,2,3,4,5]
console.log(result)   //7

4、pop()----删除原数组最后一项,并返回删除元素的值;如果数组为空则返回undefined,直接在元数组上修改;

arr= [1,2,3,4,5];
result = arr.pop(); 
console.log(arr)   //[1,2,3,4] 
console.log(result)   //5

5、push()----将参数添加到原数组末尾,并返回数组的长度,直接在元数组上修改;

arr = [1,2,3,4,5];
result = arr.push(6,7);
console.log(arr)    //[1,2,3,4,5,6,7]
console.log(result)   //7

6、concat()----数组合并,返回一个新数组,不影响原数组;

arr = [1,2,3,4,5];
result = arr.concat(6,7);
console.log(arr);   //[1,2,3,4,5] 
console.log(result);  //[1,2,3,4,5,6,7]

7、sort()----将数组从小到大排序,直接在原数组上修改;

arr = [4,5,2,3,1];
result = arr.sort();
    console.log(arr);   //[1, 2, 3, 4, 5]
console.log(result)   //[1, 2, 3, 4, 5]

8、reverse()----将数组反序,直接在原数组上修改;

arr = [4,5,2,3,1];
result = arr.reverse()
console.log(arr);   //[1, 3, 2, 5, 4]
console.log(result)   //[1, 3, 2, 5, 4]

9、slice(startIndex,endIndex)----截取起始索引startIndex 到 结束索引endIndex之间的项组成新的数组,该新数组包括起始索引startIndex所对应的项,不包括结束索引endIndex所对应的项;

arr = [1,2,3,4,5];
result1 = arr.slice(2,5);
result2 = arr.slice(2);
console.log(arr)  //[1,2,3,4,5]
console.log(result1)  //[3,4,5]
console.log(result2)  //[3,4,5]

10、join(separator)----将数组的元素组起一个字符串,以separator为分隔符,省略的话则用默认用逗号为分隔符,不影响原数组;

arr= [1,2,3,4,5];
result = arr.join("|");
console.log(arr)  //[1, 2, 3, 4, 5]
console.log(result)  //1|2|3|4|5

11、splice(start,deleteCount,val1,val2,...)----从start位置开始删除deleteCount项,并从该位置起插入val1,val2,... ,直接在原数组上修改;

arr= [1,2,3,4,5];
result1 = arr.splice(2,2,7,8,9);
console.log(arr);   //[1,2,7,8,9,5]
console.log(result1);  //[3,4]
result2 = arr.splice(0,1);  //同shift
console.log(arr);   //[2,7,8,9,5]
console.log(result2);  //[1]
arr.splice(0,0,-2,-1);   //同unshift
console.log(arr);  //[-2,-1,2,7,8,9,5]
result3 = arr.length;
console.log(result3);  //7
result4 = arr.splice(arr.length-1,1); //同pop
console.log(arr); //[-2,-1,2,7,8,9]
console.log(result4);  //[5]
arr.splice(arr.length,0,6,7);   //同push
console.log(arr);  //[-2,-1,2,7,8,9,6,7]
result5 = arr.length;
console.log(result5)  //8
返回web开发教程...