1.splice()
对数组添加/删除项目,然后返回该数组。注意:该方法会改变原始数组。
arrayObject.splice(index,howmany,item1,.....,itemX);
index:起始位置,使用负数可从数组结尾处规定位置;
howmany:要删除的元素个数,可以为0;
item1,.....,itemX参数可选;
<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" arr.splice(2,0,"William");//在arr【1】后面插入数据“William” arr.splice(2,1,"William");//删除arr【1】后面的一个数据“Thomas”,然后在该位置插入数据“William” arr.splice(2,3,"William");//删除arr【1】后面的三个数据“Thomas”、“James”,“Adrew”,然后在该位置插入数据“William” </script>
2.slice()
从已有的数组中返回选定的元素。注意:不会修改原始数组。
arrayObject.slice(start,end);
start:必须;
end:可选,不填默认选择start(含)之后的所有元素,若填,则不包含该元素(选取到arr【end-1】)
<script type="text/javascript"> var arr = new Array(3) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr.slice(1) + "<br />");//选择“John”、“Thomas”数据 document.write(arr.slice(2,4) + "<br />");//选择“Thomas”、“James”数据,不包含arr【4】 </script>
3.split()
把一个字符串分割成字符串数组。
stringObject.split(separator,howmany)
separator:必需,字符串或者正则表达式
howmany:可选,指定返回数组的最大长度;不设,则全部分割
<script type="text/javascript"> var str="How are you doing today?" document.write(str.split(" ") + "<br />");//How,are,you,doing,today? document.write(str.split("") + "<br />");//H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,? document.write(str.split(" ",3));//How,are,you "2:3:4:5".split(":"); //将返回["2", "3", "4", "5"] "|a|b|c".split("|"); //将返回["", "a", "b", "c"] "hello".split(""); //可返回 ["h", "e", "l", "l", "o"] "hello".split("", 3); //可返回 ["h", "e", "l"] </script>