The splice() method is yet another way to empty an array in JavaScript: let numbers = // empty the array Numbers = // print reference variableĬonsole. Here is an example that demonstrates the issue you may encounter when assigning a new array to an already existing array: let numbers = let numbers2 = numbers // store original array reference // reset original array Therefore, you should be careful while using this method. If you are referencing the original array from another variable or property, the original array will remain unchanged. You should only use this method when you are sure that the original array is not referenced anywhere else in the code because this actually creates a brand new empty array. Also, it doesn't mutate the original array and works in all modern and old browsers including Internet Explorer.Īnother way to remove all elements of an array is by assigning an empty array to the original variable: let numbers = // reset array Since the length property is writable, the above example will clear all elements of the array. Here is an example: const numbers = // set length to 0 The simplest method is to set the array's length property value to 0. In JavaScript, there are multiple ways available to remove all elements of an array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |