js数组操作方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js数组操作方法相关的知识,希望对你有一定的参考价值。
1. concat():当不传参数的时候,复制当前数组
var colors = ["red","green","blue"]; var colors1 = colors.concat(); //当不传参数的时候,复制当前数组 console.log(colors1 );
--输出: ["red", "green", "blue"]
concat("",[]):当传递的是数组的时候,该方法会将这些数组中的每一项都添加到结果数组中,如果传递的不是数组,这些值会被简单地添加到结果数组的末尾。
var colors2 = colors.concat("yellow",["black","brown"]); console.log(colors2 );
--输出:["red", "green", "blue", "yellow", "black", "brown"]
var parents = ["Jani", "Tove"]; var brothers = ["Stale", "Kai Jim", "Borge"]; var children = ["Cecilie", "Lone"]; var family = parents.concat(brothers, children); console.log(family);
--输出:["Jani", "Tove", "Stale", "Kai Jim", "Borge", "Cecilie", "Lone"]
2.join() 数组元素转换成字符串(默认,分隔)
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var myFruits0 =fruits.join(); console.log(myFruits0 );
--输出:Banana,Orange,Apple,Mango
3.slice() 从一个数组中选择元素,截取
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myFruits1 =fruits.slice(1,3);
console.log(myFruits1 );
--输出:["Orange", "Lemon"]
如果参数中有一个负数,则用数组长度加上该数组来确定相应的位置。如果结束位置小于开始位置,则返回空数组。
4.像数组的中部添加、删除、替换元素
(1)插入
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"Lemon","Kiwi");
console.log(fruits);
--输出: ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]
(2)删除
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,2); console.log(fruits);
--输出:["Banana", "Orange"]
(3)替换
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"Lemon","Kiwi"); console.log(fruits);
--输出:["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
以上是关于js数组操作方法的主要内容,如果未能解决你的问题,请参考以下文章