简体   繁体   中英

Default array displaying undefined value

The following Javascript function is displaying undefined value when it should display the actual value:

<script>
    function addArrayNew(a = [101], c) {
        document.write('A: ' + a[0] + '<br>');
        document.write('B: ' + a + '<br>');
        document.write('C: ' + c + '<br>');
    }

    addArrayNew(110);
</script>

Actual Output:

A: undefined
B: 110
C: undefined

Expected Output:

A: 101
B: 101
C: 110

In your example 110 gets passed as first (and only) argument so it overwrites a insted of c (which will become undefined ). It's better to put optional parameters as the last ones and then you can pass more or less arguments to your function:

 <script> function addArrayNew(c, a = [101]) { document.write('A: ' + a[0] + '<br>'); document.write('B: ' + a + '<br>'); document.write('C: ' + c + '<br>'); } addArrayNew(110); </script>

This is happening as the function description for addArrayNew has a as first argument and c as second argument. So, whatever you pass at first value for addArrayNew(110) that will be set for a only and if you pass addArrayNew(110, 100) that would be set for a first and then c. If you want to send 2nd parameter only and want a to set as default then you can pass undefined like:

 function addArrayNew(a = [101], c) { document.write('A: ' + a[0] + '<br>'); document.write('B: ' + a + '<br>'); document.write('C: ' + c + '<br>'); } addArrayNew(undefined, 110);

By passing undefined , we are actually forcing a to use the default value instead. But good practice is to always use optional parameters are last, so that by default they are set to undefined like:

 function addArrayNew(c, a = [101]) { document.write('A: ' + a[0] + '<br>'); document.write('B: ' + a + '<br>'); document.write('C: ' + c + '<br>'); } addArrayNew(110);

Here, using addArrayNew(110) or addArrayNew(110, undefined) will give you same result. But you can really understand the importance of using default values at last when you will have a large number of params to a function like:

 function addArrayNew(a, b=1, c=2, d=3, e=4, f=5) { document.write(`${a} - ${b} - ${c} - ${d} - ${e} - ${f}`); } addArrayNew(110);

As you see by putting the optional values at last, we have only call function like addArrayNew(110) instead of doing addArrayNew(undefined,undefined,undefined,undefined,undefined, 110) if a was at last.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM