Reputation: 365
I am trying to use a FOR loop to display contents of an array.
the function I want to create is similar to underscore.js _.rest function except the objective is touse a FOR loop.
rest(anyArray, n);
so if I were to enter "rest([1,2,3,4,5], 3);", I want to return "[4,5]".
Here is what I have and it does not work:
rest: function (anyArray, n) {
var isArray = (anyArray instanceof Array),
isNum = (typeof n === 'number'),
result = new Array,
valRange = (n >= 0);
if (isArray && isNum) {
for (len = anyArray.length, i = 0, j = (len - (n + len)); i < j, n < len; i++, j++) {
result[i] = anyArray[j];
}
return result;
}
}
Upvotes: 0
Views: 372
Reputation: 191779
rest: function (anyArray, n) {
return anyArray.slice(n);
}
rest: function (anyArray, n) {
var output = [];
for (; n < anyArray.length; n++) {
output.push(anyArray[n]);
}
return output;
}
Upvotes: 1
Reputation: 664971
The part that leads to "not working" is j = (len - (n + len))
: Essentially, you say j = n
, and then you are looping while i < j
. I'd expect that what you actually want is j < len
. Also, you should add the var
keyword:
rest: function(anyArray, n){
var isArray = (anyArray instanceof Array),
isNum = (typeof n === 'number'),
result = [];
if (isArray && isNum) {
for (var len = anyArray.length, i = 0, j = n; j < len; i++, j++) {
result[i] = anyArray[j];
}
return result;
}
// else?
}
Of course, just using the native slice
method would be much easier.
Upvotes: 0