Home > Mobile >  Arguments Object
Arguments Object

Time:12-28

i'm currently learning js and need to pass a test, every requirement checks out besides "should work on an arguments object". I noticed that when I take out the Array.isArray() part of the code, it works. However then I wont pass the "return an empty array if array is not an array" part of the test.

we are allowed to ask for help on stackoverflow so I would appreciate the help. thanks :)

this is my code:

// Return an array with the first n elements of an array.
// If n is not provided return an array with just the first element.
_.first = function (array, n) {
  var resultArray = [];
  if (Array.isArray(arguments[0]) !== true){
    return []} 
  else if (arguments[1] > arguments[0].length){
  return arguments[0]
 } else if (typeof arguments[1] !== "number" || arguments[1] == 0 || arguments[1] < 0){
  resultArray.push.call(resultArray, arguments[0][0])
  return resultArray
 } else {
 for (var i = 0; i < arguments[1]; i  )
 resultArray.push.call(resultArray, arguments[0][i]);
 return resultArray;
}
};

CodePudding user response:

That's because the requirements expects you use somewhere the variable argument array. Instead you use arguments[0].

So use the first over the latter.
Likewise, use n instead of arguments[1]

CodePudding user response:

You can use Array.prototype.slice function simply

const first = (array = [], n = 1) =>
    Array.isArray(array) ? array.slice(0, array.length >= n ? n : 1) : [];

If n > array.length this will return the whole array.

  • Related