In: Computer Science
Define a JavaScript function named prepend that has two parameters. The first parameter is an array of Strings. The second parameter is a String. Your function should use the accumulator pattern to return a newly created array whose elements are the concatenation of the second parameter with the element at the same index in the first parameter.
Code:
Everything About Code is Explained in comments of code:
//Here is Definition of Prepend Function
function prepend(string_array, string){
//creating new array
var arr=new Array(string_array.length);
//using the accumulator pattern to iterate with for loop
// to create the contents of new array
for(var i=0;i<string_array.length;i++){
arr[i]=string+string_array[i];
}
return arr; //returning the newly created array
}
//Printing line
console.log("The array after prepending is: ");
//calling prepend Function and printing the array
console.log(prepend(["portant", "possible", "mature"], "im"));
Output:
Thanks.