Why can't I call an array method on a function's arguments?

前端 未结 8 1297
鱼传尺愫
鱼传尺愫 2020-12-03 05:07

I have a function that can accept any number of arguments...

const getSearchFields = () => {        
    const joined = arguments.join(\'/\'); 
};
         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 05:45

    The problem is that arguments is an array-like object (it has numbered properties mapping to the passed arguments and a length property), but it actually isn't an array.

    In the old days, you could make it into a real array with Array.prototype.slice.call(arguments) (among other methods).

    However, we're a bit luckier these days (depending on your supported platforms of course). You can either do...

    const getSearchFields = (...args) => {
       Array.isArray(args); // true
    };
    

    ...or...

    const getSearchFields = () => {
       const args = Array.from(arguments);
       Array.isArray(args); // true
    };
    

    The first example is preferred because...

    • you get the normal array creation without an extra step in the function body
    • arguments is a magic variable (it's not defined explicitly, so where did it come from?)
    • it has funny behaviour with named args in non-strict mode (note that you should always 'use strict')
    • the first example has much clearer intent (the creation of an array of all arguments is explcit).

提交回复
热议问题