Forum Moderators: open
Do i need to make an array or does a variable with "[]" do it?
Here is what I have and it says element is undefined.
JS:
function applyFunction(arr,func){
for(var arr=0;arr<=4;arr++);
}
function square(element) {
return element * element;
}
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="apFunc.js" language="JavaScript" type="text/javascript"></script>
</head>
<script>
var arr = [1,2,3,4];
var arr1=applyFunction(arr,square);
document.write(arr1);
</script>
<body>
</body>
</html>
Thanks for any help.
For example:
var arr = [1,2,3,4];
That is an array containing 4 number items. The item at index 0 is the number 1. The item at index 1 is the number 2, and so on.
You applyFunction method needs a little tweaking. First, you'll want a variable to store the return value (this is going to be an array of the same size as the array that was passed in, and we're going to leave the original array unchanged):
function applyFunction(arr, func) {
var result = [];
//...
return result;
}
Next, you want to loop through the array that was passed in:
var i, n = arr.length;
for (i = 0; i < n; i++) {
//...
}
function applyFunction(arr, func) {
var result = [], i, n = arr.length;
for (i = 0; i < n; i++) {
//...
}
return result;
}
function applyFunction(arr, func) {
var result = [], i, n = arr.length;
for (i = 0; i < n; i++) {
result[i] = func(arr[i]);
}
return result;
}
Side Note: don't include the language="JavaScript" attribute on your script tag. It's invalid and is not needed. Also note, in general it's best to avoid using document.write... instead use DOM methods to append to the DOM or assign values to innerHTML of elements.
Something like this:
var arr1 = [1, 2, 3, 4];
var arr2 = [5, 6, 7, 8];
appendArray(arr1, arr2);
where the appendArray creates this [1,2,3,4,5,6,7,8]
can I add the second array to the index of arr1 in the function or is that reserved for only adding a new element?
function appendArray(ar1, ar2){
var result = [], i, n = ar1.length;
for (i = 0; i < n; i++) {
result[i] = (ar1[i]+ ar2[i]);
}
document.write(result[i]);
}
Thanks for the help I'm stuck on this.