一. 数组常用方法
1. concat()
连接两个或更多的数组,并返回结果。
<script type="text/javascript"> var array1 = [1,2,3]; var array2 = [4,5]; var array3 = array1.concat(array2); console.log(array3); //1,2,3,4,5 </script>
2. pop()
删除并返回数组的最后一个元素
<script type="text/javascript"> var array1 = [1,2,3]; var temp = array1.pop(); console.log(temp);//3 console.log(array1.length);//2 </script>
3. push()
向数组的末尾添加一个或更多元素,并返回新的长度。
<script type="text/javascript"> var array1 = ["a","b","c"]; var temp = array1.push("d","e"); //返回新的长度 console.log(array1); // ["a", "b", "c", "d", "e"] console.log(temp);//5 </script>
另外因为push和unshift都是可变参数,所以可以一次传入多个参数,也可以一次传入一个数组,但是如果传入一个数组,该数组将作为单个数组元素来看待,以push为例:
<script type="text/javascript"> var array1 = ["a","b","c"]; var array2 = ["d","e"] var temp = array1.push(array2); //返回新的长度 console.log(array1); // ["a", "b", "c", Array(2)] console.log(temp);//4 </script>
4. shift()
删除并返回数组的第一个元素
<script type="text/javascript"> var array1 = [1,2,3]; var temp = array1.shift(); console.log(temp);//1 console.log(array1.length);//2 </script>
5. unshift()
向数组的开头添加一个或更多元素,并返回新的长度。
<script type="text/javascript"> var array1 = ["a","b","c"]; var temp = array1.unshift("d","e");//返回新的长度 console.log(array1); //["d", "e", "a", "b", "c"] console.log(temp);//5 </script>
6. splice()
指定位置删除指定个元素,并将删除的元素返回:
<script type="text/javascript"> var array1 = ["a","b","c","d","e"]; var temp = array1.splice(1,2);//从下标为1的元素开始,向后删除二个元素,并且将其返回 console.log(array1); // ["a", "d", "e"] console.log(temp);// ["b", "c"] </script>
还可以删除的同时,添加元素:
<script type="text/javascript"> var array1 = ["a","b","c","d","e"]; var temp = array1.splice(1,2,"f","g","h");//从下标为1的元素开始,向后删除二个元素,并且将其返回,然后从下标1开始添加三个元素 console.log(array1); // ["a", "f", "g", "h", "d", "e"] console.log(temp);// ["b", "c"] </script>
请登录之后再进行评论