How best to determine if an argument is not sent to the JavaScript function

后端 未结 13 644
猫巷女王i
猫巷女王i 2020-11-28 00:40

I have now seen 2 methods for determining if an argument has been passed to a JavaScript function. I\'m wondering if one method is better than the other or if one is just ba

相关标签:
13条回答
  • 2020-11-28 01:37

    There are significant differences. Let's set up some test cases:

    var unused; // value will be undefined
    Test("test1", "some value");
    Test("test2");
    Test("test3", unused);
    Test("test4", null);
    Test("test5", 0);
    Test("test6", "");
    

    With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined, null, 0, and "" into the boolean false. And if you were to use Tom's method, only the fourth test will use the default!

    Which method you choose really depends on your intended behavior. If values other than undefined are allowable for argument2, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.

    0 讨论(0)
提交回复
热议问题