To add an element to the beginning of an array in TypeScript, you can make use of the built-in unshift()
method. This method adds one or more elements to the beginning of an array and returns the new length of the modified array.
Here's an example:
index.ts146 chars4 lines
In this example, we define an array myArray
with some initial values. Then, we call the unshift()
method with the argument 1
, which adds the value 1
to the beginning of the array. Finally, we log the modified array to the console to verify that the element was added successfully.
Note that this method modifies the original array, and returns its new length. If you want to add an element to the beginning of an array without modifying the original array, you can use the spread operator to create a new array with the additional element:
index.ts130 chars4 lines
In this example, we create a new array newArray
by spreading the original array myArray
into it using the spread operator (...
). We place the new element 1
before the spread operator, so it gets added to the beginning of the new array. Finally, we log the new array to the console to verify that it contains the additional element.
gistlibby LogSnag