I need to write a function that takes two arguments, a number to start and a number to end a range. The function returns an array of the range including start and end. Also, I need to test the arguments: If they are not numbers return a meaningful message and an array of ALL the arguments. I now how to write this function with numbers but not with Strings.
Asked
Active
Viewed 550 times
-2
-
For numbers I have two prompts with start and end. Also I have an empty array. With a for loop I save all numbers in my empty array. This works fine. But I don't know how to do this with strings. – Nov 02 '18 at 16:19
-
can you edit to question with your comment, and some code if possible – Ayush Gupta Nov 02 '18 at 16:20
2 Answers
1
Here is an example.
This will take the two numbers given and populate the array from smallest to largest.
You can can then decide how to handle the array after that.
let arr = []; //create array
let numOne = validateNumber();
let numTwo = validateNumber();
createArray(numOne, numTwo); // call function to populate array
arr.forEach(number => {
console.log(number);
})
function validateNumber(){
let pass = false;
let number = 0;
while (!pass){
number = parseInt(prompt('Enter a number'));
if (Number.isInteger(number)) pass = true;
}
return number;
}
function createArray(numOne, numTwo){
var start = numOne;
var end = numTwo;
if (numOne > numTwo){
start = numTwo;
end = numOne;
}
for (var i = start; i <= end; i++) {
arr.push(i)
}
}

Christheoreo
- 373
- 3
- 15
0
You could create a function like the one below to get started.
function returnRange(start, end) {
//Array to store numbers in.
var myarray = [];
// Check if the provided parameters are numbers and return an error message if they are.
// Else add the range of numbers to the array
if (isNaN(start) || isNaN(end)) {
console.log("One of these is not a number:");
console.log("start = " + start + " end = " + end);
} else {
//Loop through your input and store into an array
for (var i = start; i < end + 1; i++) {
myarray.push(i);
}
// You can use console.log(myarray) here to verify it is returning the correct range
return myarray;
}
}
returnRange(1,5);

crumdev
- 1,599
- 2
- 11
- 13
-
You code works fine but I need a function where it's possible to add strings/chars in an array. – Nov 02 '18 at 16:57
-
Sorry the question was not clear. I would check this answer out then. https://stackoverflow.com/questions/12376870/create-an-array-of-characters-from-specified-range – crumdev Nov 02 '18 at 17:02