简体   繁体   中英

Function call not displaying undefined value when an array is passed as param

I have created the following function in JavaScript which is working as expected:

<script>
    function add(a, b, c) {
        document.write('A: ' + a + '<br>');
        document.write('B: ' + b + '<br>');
        document.write('C: ' + c + '<br>');
    }
add(10, 20);
</script>

Output:

A: 10
B: 20
C: undefined

However, the following function in JavaScript is not working as expected wherein it is not displaying undefined value

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

Output:

A: 110
B: 110

As per my understanding the output should be as below:

Expected Output:

A: 110
B: 110
C: undefined

Also, what is difference between a[0] and a in the above example?

c is never declared

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

 The difference between a[0] and a is that a[0] is displaying the first index value of an 
 array and a is displaying all the values of the array.

 Imagine A=[100,200]
 document.write('A: ' + a[0] + '<br>');
 Would write 100
 document.write('A: ' + a + '<br>');
 Would write 100,200

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