Wednesday, May 19, 2021

Javascript Practice 52: JS Hero - Set array elements

 
Question: 

Write a function setFirstElement that takes an array and an arbitrary variable. The variable should be inserted as the first element in the array. The array should be returned.

Example: setFirstElement([1, 2], 3) should return [3, 2].




Answer: 

function setFirstElement (array, v1) {
array[0] = v1; 
return array
}





> declare a function setFirstElement 
> it has 2 parameters array & v1
> we set the first element of the array to the v1 parameter
> like this: array[0] = v1
> we return the array
> we learnt how to get the element of an array in the last exercise
> and now we learnt how to set an element in this exercise

No comments:

Post a Comment