Reputation: 4735
I have a function that searches for a specified number in an array and returns the value that was searched for, the length of the array and the index in which the array was in.
I have 3 questions:
Code:
function include(arr, obj) {
for(var i=0; i< arr.length; i++) {
if (arr[i] == obj)
return [i, obj, arr.length];
}
}
var a = include([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 6); // true
console.log("You searched for the value: " + a[1]);
console.log("The length of the array is: " + a[2]);
console.log("The Index of the value(" + a[1] + ") from " + "'first array element'" + " to " + (a[2]) + " is: " + a[0]);
console.log(include([1,2,3,4], 6)); // undefined
Upvotes: 0
Views: 38
Reputation: 13294
Per question:
indexOf
.function include(arr, obj) {
var returned = -1;
returned = arr.indexOf(obj); //get the index of the search criteria. It will return -1 if not found.
console.log("You searched for the value: " + obj); //obj will be the search value
if (returned != -1)
{
console.log("The length of the array is: " + arr.length); //arr.length gives us the length of the array;
console.log("The Index of the value ("+obj+"): " + returned); //returned gives us the index value.
}
else
{
console.log("It was not found");
}
return returned;
}
var a = include([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 6); // true
You can use the obj
argument which is the search criteria and array.length
to get the length of the array. I improved the functionality to use array.indexOf
removing the need for a loop.
A for loop will do that:
var newArray = [];
for (var i = 0; i < 400; i++)
{
array.push(i+1); //will push 400 values into the array.
}
Upvotes: 2
Reputation: 154
First: do you mean something like this?
function report(a) {
console.log("You searched for the value: " + a[1]);
console.log("The length of the array is: " + a[2]);
console.log("The Index of the value(" + a[1] + ") from " + "'first array element'" + " to " + (a[2]) + " is: " + a[0]);
}
Second, to get the first array element you could access arr[0]. Why not return arr itself from include(), like so?
function include(arr, obj) {
for(var i=0; i< arr.length; i++) {
if (arr[i] == obj)
return [i, obj, arr];
}
}
Then:
console.log("The Index of the value(" + a[1] + ") from " + arr[0] + " to " + arr.length + " is: " + a[0]);
As for defining a range of numbers, JS has no native way to do this but you could use the Underscore library's _.range() method, or extend Javascript's Array like this!
Upvotes: 1