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

前端 未结 8 1279
鱼传尺愫
鱼传尺愫 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).
    0 讨论(0)
  • 2020-12-03 05:50

    You have to make assignment to a variable for it to work.

    var a = ['Wind', 'Rain', 'Fire'];
    
    var myVar1 = a.join();
    
    var myVar2 = a.join(', ');
    
    var myVar3 = a.join(' + ');
    
    var myVar4 = a.join('');
    
    0 讨论(0)
提交回复
热议问题