javascript The appFunc code should then repeatedly call the parameter function o
ID: 3604439 • Letter: J
Question
javascript
The appFunc code should then repeatedly call the parameter function on each element in the array, storing the result back into the array at the same point. Write a function called appFunc that receives an array (arr) and a function (func) as a parameter. appendArray that receives two arrays (arr1 and arr2). The function should use a loop append all the elements of arr2 on the end of arr1. no methods of Array class that will perform the operation for you in one step
function sq(ele) {
return ele * ele;
}
var arr = [1, 2, 3, 4];
appFunc(arr, sq);
Explanation / Answer
function sq(ele) {
return ele * ele;
}
function appFunc(arr,sq){
//loop through array
for(i=0;i<arr.length;i++){
//call function with arr[i] and store in arr[i]
arr[i] = sq(arr[i]);
}
}
function appendArray(arr1,arr2){
//loop through arr2
for(i=0;i<arr2.length;i++){
//push element from arr2 to arr1
arr1.push(arr2[i]);
}
}
var arr = [1, 2, 3, 4];
appFunc(arr, sq);
console.log(arr);
var arr2 = [5,6,7,8];
appendArray(arr,arr2);
console.log(arr);
/*
sample output
[ 1, 4, 9, 16 ]
[ 1, 4, 9, 16, 5, 6, 7, 8 ]
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.