Hello I am new this is my first question. I am completing the JavaScript Primer for Bloc, and am stuck on a simple checkpoint.
I am trying to Create a function named arrayLengthPlusOne. This function should: take one argument, an array return a number that is one greater than the number of elements in the array.. For example: arrayLengthPlusOne([0,0,1,0,2,1]); // returns 7
code i tried:
var arrayLengthPlusOne = function () { return arrayLengthPlusOne.length + 1; };
I am getting an error message telling me it isnt' passing tests. Maybe i'm not grasping the array/function relationship. I understand that an array is an Object not a Data Type. How do i make my function take one argument, that IS an array ?
-
1please add your code, you tried. please have a look here: minimal reproducible exampleNina Scholz– Nina Scholz2016年08月29日 06:29:00 +00:00Commented Aug 29, 2016 at 6:29
5 Answers 5
Only you need to add an argument in your function declaration.
var arrayLengthPlusOne = function(data) { // data is an argument in the function. It's an array.
return data.length + 1;
};
// Calling the function.
var arrayData = [0, 1, 3, 4]; // Declare an array variable with four elements.
alert(arrayLengthPlusOne(arrayData)); // Show an alert with the result. Returns 4 + 1 elements.
Comments
The problem is your variabel name "arrayLengthPlusOne" in the function.
You should do something like:
var arrayLengthPlusOne = function (yourArray) { return yourArray.length + 1; }
and the call the function
myArray = [1 ,2 ,3 ,4 ]
arrayLengthPlusOne(myArray)
Comments
you need to pass the array as a parameter
var arrayLengthPlusOne = function(array) {
return array.length + 1;
}
2 Comments
Inside the function you can check whether the parameter passed is an array or not. If the parameter is an array it returns the length added by 1. If it's not an array, it returns undefined. However you can change the return type based on your requirement
var arrayLengthPlusOne = function (array1) {
if (array1 instanceof Array) {
return array1.length + 1;
}
};
Comments
You are missing to pass the arguments to the function. Try this one:
alert(arrayLengthPlusOne([1,2,3,4,5,6]));
var arrayLengthPlusOne = function (myArray) {
return myArray.length + 1;
};