js 数组的添加和删除方法

1. shift() 方法:把数组的第一个元素删除,并返回删除的元素值。(会改变原数组)

var movePos= [11,22];
movePos.shift()
console.log(movePos)//[22]
alert(movePos)//22

document.write(movePos.length);//1

2.concat() 方法:用于连接两个或多个数组,并返回一个新数组。(不会改变原数组) 

var movePos=[11,22];

var arr=movePos.concat(4,5);
console.log(arr);//[11, 22, 4, 5]
alert(arr);//11, 22, 4, 5

var ar1=[2,3]
var ar3=[1111,2222];
var ar2=arr.concat(ar1,ar3);
console.log(ar2); //[11, 22, 4, 5, 2, 3, 1111, 2222]
alert(ar2); //11, 22, 4, 5, 2, 3, 1111, 2222

document.write(arr.length);//4

document.write(ar2.length);//8

 3. join() 方法:把数组中的元素放入一个字符串。元素是通过指定的分隔符进行分隔的。

返回一个字符串。该字符串是通过把 arrayObject 的每个元素转换为字符串,然后把这些字符串连接起来,在两个元素之间插入separator 字符串而生成的。

var movePos=[11,22];

var arr=movePos.join("+");
document.write(arr)  //11+22

4. pop() 方法:把数组最后一个元素删除,并返回最后一个元素的值, 如果数组为空则返回undefined。(会改变原数组)

var movePos=[11,22,33];
var arr= movePos.pop();
document.write(arr)  //33

document.write(arr.length)//2  

5.push() 方法:向数组末尾添加一个或多个元素,并返回数组长度。(会改变原数组)

var movePos=[11,22];

var arr= movePos.push("333");

document.write(arr)  //返回的结果就是数组改变后的长度:3

document.write(arr.length)  //undefined

6.reverse() 方法:用于颠倒数组元素的顺序,返回新的数组。

var movePos=[11,22];

var arr=movePos.reverse();

document.write(arr)  //返回新的数组:22,11

document.write(arr.length)  //返回数组长度2

7.slice() 方法:从数组截取的元素,返回截取的元素 slice(开始位,结束位)。

var movePos=[11,22,33];

var arr= movePos.slice(1,2); //(开始位, 结束位);

document.write(arr)  //返回截取的元素:22

document.write(arr.length)  //返回数组长度1,截取的数组的长度

8.splice() 方法:向/从数组添加/删除项目,返回新的数组。(会改变原数组) ???????

var movePos=[11,22,33,44];

var arr= movePos.splice(1,2);  //movePos.splice(开始位, 删除的个数);

document.write(arr) ; //返回新的数组:[22,11]

document.write(arr.length) ;//返回数组长度2

    var movePos =[111,222,333,444];

    movePos.splice(2,1,"666") //movePos.splice(开始位, 删除元素的个数,向数组添加的新项目。);从下标2开始删除一位,并用666替换删除下表位置的元素
    document.write(movePos + "<br />")  //[111,222,"666",444];

9.unshift() 方法:从数组的开头添加一个或更多元素,并返回数组的长度 

var movePos =[111,222,333,444];
movePos.unshift("55555")
document.write(movePos + "<br />")//55555,111,222,333,444


10.sort(orderfunction):按指定的参数对数组进行排序 
var movePos =["444","111","333","222"];

movePos.sort(1)

document.write(movePos + "<br />")//55555,111,222,333,444

转载原文地址:https://www.cnblogs.com/js0618/p/6283724.html

猜你喜欢

转载自blog.csdn.net/qq_38719039/article/details/82831029