标签:
//数组的方法
//1. concat() (concat的英文释义:合并数组;合并多个字符串;)
var colors = ["red", "green", "blue"];
var color2 = colors.concat("yellow", ["black", "brown"]);
console.log(colors);//["red", "green", "blue"]
console.log(color2);//["red", "green", "blue", "yellow", "black", "brown"]
//总结: concat合并数组,原数组不变,新的数组由原数组和concat中传递的参数数组
//2. slice() slice的英文释义:切成片;切下;划分;
var colors = ["red", "green", "blue", "yellow", "purole"];
var color2 = colors.slice(1);
var color3 = colors.slice(1, 3);
console.log(colors);//"red", "green", "blue", "yellow", "purole"]
console.log(color2);//["green", "blue", "yellow", "purole"]
console.log(color3);//["green", "blue"]
//总结: slice(x, y)剪切数组,原数组不变, x开始剪切的数组下标,y结束的位置但不包括该位置即最终得到的是y下标前一个位置的值;x和y的值可以为负数,数组的最后一个元素的下标为-1, 如果x,y都是负数,则array.slice(x, y)与array.length(x + array.length, y + aray.length)的结果相同。若只有一个值,则从该值开始剪切一直到数组的结束
//3. splice() (最强大的数组方法) (splice英文释义: 绞接; 捻接(两段绳子); 胶接; 粘接(胶片、磁带等);
//删除
var colors = ["red", "green", "blue"];
var remove = colors.splice(0, 1);
console.log(colors);//["green", "blue"]
console.log(remove);//["red"]
//插入
remove = colors.splice(1, 0, "yellow", "orange");
console.log(colors);//["green", "yellow", "orange", "blue"]
console.log(remove);//[]
//替换
remove = colors.splice(1, 1, "red", "purple");
console.log(colors);//["green", "red", "purple", "orange", "blue"]
console.log(remove);//["yellow"]
//总结:splice(x, y)两个参数的时候为删除,x为开始删除的位置, y为删除的个数,返回值为删除的数组元素
// splice(x, 0, "red", "green"), x为开始删除的位置, 0为删除的个数,会在数组的x位置后面开始插入第三个以后的参数,返回值为一个空数组,因为什么都没有嘛
// splice(x, y, "red", "green"), x为开始删除的位置, y为删除的个数,先删除后再从x位置开始添加即为替换, 返回值为删除的数组元素
标签:
原文地址:http://www.cnblogs.com/lovesilence/p/5781986.html