首页 > 代码库 > Js数组

Js数组

Array.prototype.slice()

slice() 方法会浅复制(shallow copy)数组的一部分到一个新的数组,并返回这个新数组;

slice 不修改原数组,只会返回一个浅复制了原数组中的元素的一个新数组;

语法:slice([begin[, end]]) ,如果 end 被省略,则slice 会一直提取到原数组末尾
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; 
var citrus = fruits.slice(1, 3);
//输出["Orange", "Lemon"]

Array.prototype.concat()

concat() 方法将传入的数组或非数组值与原数组合并,组成一个新的数组并返回.不修改原数组

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
var alpha = ["a", "b", "c"];var numeric = [1, 2, 3];// 组成新数组 ["a", "b", "c", 1, 2, 3]; 原数组 alpha 和 numeric 未被修改var alphaNumeric = alpha.concat(numeric);

Array.prototype.filter()

filter() 方法使用指定的函数测试所有元素,并创建一个包含所有通过测试的元素的新数组。

filter 不会改变原数组

var new_arrary = arr.filter(callback[, thisArg])
function isBigEnough(element) {  return element >= 10;}var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Array.prototype.splice()


splice() 方法用新元素替换旧元素,以此修改数组的内容。

array.splice(start, deleteCount[, item1[, item2[, ...]]])

如下代码演示了 splice 的用法:

var myFish = ["angel", "clown", "mandarin", "surgeon"];//从第 2 位开始删除 0 个元素,插入 "drum"var removed = myFish.splice(2, 0, "drum");//运算后的 myFish:["angel", "clown", "drum", "mandarin", "surgeon"]//被删除元素数组:[],没有元素被删除//从第 3 位开始删除 1 个元素removed = myFish.splice(3, 1);//运算后的myFish:["angel", "clown", "drum", "surgeon"]//被删除元素数组:["mandarin"]//从第 2 位开始删除 1 个元素,然后插入 "trumpet"removed = myFish.splice(2, 1, "trumpet");//运算后的myFish: ["angel", "clown", "trumpet", "surgeon"]//被删除元素数组:["drum"]//从第 0 位开始删除 2 个元素,然后插入 "parrot", "anemone" 和 "blue"removed = myFish.splice(0, 2, "parrot", "anemone", "blue");//运算后的myFish:["parrot", "anemone", "blue", "trumpet", "surgeon"]//被删除元素的数组:["angel", "clown"]//从第 3 位开始删除 2 个元素removed = myFish.splice(3, Number.MAX_VALUE);//运算后的myFish: ["parrot", "anemone", "blue"]//被删除元素的数组:["trumpet", "surgeon"]

Js数组