June 7, 2023
Program to use JavaScript Array splice() method
let a = [1, 2, 3, 7, 5];
let b = a.splice(3, 1, 4);
console.log(a);
console.log(b);
Output
[1, 2, 3, 4, 5]
[7]
Steps Description
- Declare two variable
a
andb
- Initialize two variable with value of array
a = [1, 2, 3, 7, 5]
andb = a.splice(3, 1, 4)
- Array
splice()
method adds or removes an array element and returns the removed element. - The value of
b
variable is displayed with the help of console.log inbuilt function
Program to use JavaScript Array splice() method
let c = [2, 44, 32, 8, 10, 12, 14, 16, 18, 20];
let d = c.splice(1, 2, 4, 6)
console.log(c);
console.log(d);
Output
[
2, 4, 6, 8, 10,
12, 14, 16, 18, 20
]
[ 44, 32 ]
Steps Description
- Declare two variable
c
andd
- Initialize two variable with value of array
c = [2, 44, 32, 8, 10, 12, 14, 16, 18, 20]
andd = c.splice(1, 2, 4, 6)
- Array
splice()
method adds or removes an array element and returns the removed element. - The value of
d
variable is displayed with the help of console.log inbuilt function
Program to use JavaScript Array splice() method
let e = ['Cat', 'Dog', 'Tiger', 'Lion'];
let f = e.splice(2, 0, 'Elephant', 'Bear');
console.log(e);
console.log(f);
Output
[ 'Cat', 'Dog', 'Elephant', 'Bear', 'Tiger', 'Lion' ]
[]
Steps Description
- Declare two variable
e
andf
- Initialize two variable with value of array
e = ['Cat', 'Dog', 'Tiger', 'Lion']
andf = e.splice(2, 0, 'Elephant', 'Bear')
- Array
splice()
method adds or removes an array element and returns the removed element. - The value of
f
variable is displayed with the help of console.log inbuilt function
by : Suhel Akhtar
Quick Summary:
Array element can be added and removed in JavaScript array splice() method