//splice()方法,向数组中插入项,插入方式有3种 //1、删除----可以删除任意数量的项,只需指定2个参数:要删除的第一项的位置和要删除的项数 var colors = ["red", "green", "yellow", "black", "brown"]; var removed = colors.splice(1,3); console.log(removed);//["green", "yellow", "black"] 从第1个位置开始,删除3个 console.log(colors);//["red", "brown"] //2、插入----可以向指定位置插入任意数量的项,只需提供3个参数:起始位置、0(要删除的项数)、要插入的项(如果要插入多个项,可以再传入第4,第5以至任意多个项)。 var colors2 = ["red", "green", "yellow", "black", "brown"]; colors2.splice(2, 0, "orange", "blue"); console.log(colors2);//["red", "green", "orange", "blue", "yellow", "black", "brown"] 从第2个位置插入orange, blue //3、替换--原理和插入差不过,插入把第2个参数设置为0,替换则把0改为你想要替换的项目个数就行了 var colors3 = ["red", "green", "yellow", "black", "brown"]; var removed3 = colors2.splice(2, 3, "orange", "blue"); console.log(removed3);//["yellow", "black", "brown"] 从第2个位置开始删除3个 console.log(colors3);//["red", "green", "orange", "blue"] 从第2个位置删除3个,并插入orange, blue