37
loading...
This website collects cookies to deliver better user experience
splice()
method slice()
method splice()
method slice()
method let arr1=[1,2,3,4,5]
let arr2=[1,2,3,4,5]
arr1.splice(1,3) //returns [2, 3, 4]
console.log(arr1) //[1, 5]
arr2.slice(1,3) //returns [2, 3]
console.log(arr2) //[1, 2, 3, 4, 5]
splice(start, deleteCount, item1, item2,... itemN)
If deleteCount
is 0
or negative, no elements will be deleted.
item1, item2...itemN(optional) ->The elements to add to the array, beginning from start.
If you do not specify any elements, splice()
will only remove elements from the array.
let a = [1,2,3,4,5]
a.splice() //[]
console.log(a) // [1,2,3,4,5]
let a = [1,2,3,4,5]
a.splice(2) //returns [3,4,5]
console.log(a) //[1,2]
let a=[1,2,3,4,5]
a.splice(-3) //returns [3,4,5], here start is treated as array.length-start
console.log(a) //[1,2]
let a=[1,2,3,4,5]
a.splice(-7) //returns [1,2,3,4,5], here start is treated as array.length-start and this is ngative so start will now be treated as 0
console.log(a) //[]
//(an empty array)
let a=[1,2,3,4,5]
a.splice(2,9) //returns [3,4,5]
console.log(a) //[1,2]
let a=[1,2,3,4,5]
a.splice(2, 2, 'a','b','c','d') //returns [3, 4]
console.log(a) //[1, 2, "a", "b", "c", "d", 5]
//slice has removed 2 elements starting from index '2' and added the item1, item2, ...itemN at start positon
slice(start, end)
start
is undefined, slice
starts from the index 0
.end
is omitted, then its treated as array.lengthlet arr=[1,2,3,4,5]
arr.slice() //returns [1,2,3,4,5]
arr.slice(2) //returns [3,4,5]
console.log(arr) //[1,2,3,4,5]
arr.slice(2,1) //returns []
console.log(arr) //[1,2,3,4,5]
arr.slice(2,-1) //returns [3,4], here end is treated as arr.length-1 which is 4 i.e arr.slice(2,4)
console.log(arr) //[1,2,3,4,5]
arr.slice(2,9) //[3,4,5]
console.log(arr) //[1,2,3,4,5]
Array.prototype.slice.call(arguments)
let array_like_obj={
0: 'john',
1: 'doe',
2: 'capscode',
length: 3
}
console.log(Array.prototype.slice.call(array_like_obj))
//["john", "doe", "capscode"]