When erasing elements of an array from JavaScript

Asked 2 years ago, Updated 2 years ago, 109 views

When you erase elements of an array in JavaScript, you use the delete operator or the array's method, splice. What's the difference between these two?

myArray = ['a', 'b', 'c', 'd'];

//delete myArray[1];      
//myArray.splice (1, 1);

Please show the difference between delete and splice in this situation.

javascript array

2022-09-22 22:08

1 Answers

If you write delete first,

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray
  [undefined, "b", "c", "d"]

undefined takes over the erased element. And

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

If you use the splice, that part is erased in this way, and then you pull the next part to fill the space.


2022-09-22 22:08

If you have any answers or tips

Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656

© 2024 OneMinuteCode. All rights reserved.