var _ = {};
Underscore's first function will return the first, n , items in an array. So for example, if you call first and give it 4 as an argument, then first will return the first 4 items in the array.
_.first = function(array, n) {
return n === undefined ? array[0] : array.slice(0, n)
}
So, first takes two arguments, the collection or array, and the number you feed it. If no argument is fed for n, then it will just return the first item in the array, else, it will start at the zero index, and stop at which ever number is fed in for n.
It literally reads like this: return this value : if n is equal to undefined then return the first item in the array, if it's not equal to undefined, then slice the array starting with index 0 and ending at index n.
If you're not sure how slice works in javascript, then google it. If you don't know how to call out items in an array using bracket notation, then google that too. If the conditional statement above is confusing to you, note you could write it out using if/else statements, but the above is easier and cleaner. Here's the same function written in if/ else statements:
_.first = function(array, n){
if(n === undefined){
return array[0];
}
else{
return array.slice(0, n);
}
}
No comments:
Post a Comment