0

I'm using cordova in combination with coffeescript and I try to shuffle an Array. While debugging why my function does not work, I noticed that an Array I created does not behave as it should. Consider the following piece of code:

shuffleArray: (arr) ->

  $log.log("arr:")
  $log.log(arr)

  arr2 = new Array(arr.length)
  $log.log("arr2 at beginning: " + JSON.stringify(arr2))
  i = 0
  while i < arr.length
    $log.log("i: " + String(i))
    $log.log("ARRAY BEFORE ASSIGNING: ")
    $log.log(arr2)

    valueToAssign = arr[i]
    $log.log("value to assign:")
    $log.log(valueToAssign)
    arr2[i] = valueToAssign
    $log.log("array after assigning: ")
    $log.log(arr2)
    i += 1

  $log.log("arr2 at the end: ")
  $log.log(arr2)

  # ...

When executed with arr=[1,2,3] I get the following result:

[Log] arr: 
[Log] [1, 2, 3] 
[Log] arr2 at beginning: [null,null,null] 
[Log] i: 0 
[Log] ARRAY BEFORE ASSIGNING:  
[Log] [3, 2, 1] 
[Log] value to assign: 
[Log] 1
[Log] array after assigning:  
[Log] [3, 2, 1] 
[Log] i: 1 
[Log] ARRAY BEFORE ASSIGNING:  
[Log] [3, 2, 1] 
[Log] value to assign: 
[Log] 2 
[Log] array after assigning:  
[Log] [3, 2, 1] 
[Log] i: 2 
[Log] ARRAY BEFORE ASSIGNING: 
[Log] [3, 2, 1] 
[Log] value to assign: 
[Log] 3 
[Log] array after assigning: 
[Log] [3, 2, 1]
[Log] arr2 at the end:  
[Log] [3, 2, 1] 

While expecting "ARRAY BEFORE ASSIGNING" to be [null, null, null] the first time there are values yet. Let me state out that this order is random and changes from execution to execution.

So there are two things I cannot figure out:

  1. Why does arr2 change between when entering the while loop?

  2. Why does array value assigning not work?

And additionally: Why does this not happen when embedded to Android?

Thank you!

hmoews
  • 116
  • 5

1 Answers1

0

This is probably due to the exact point in time when the values are read in the log. Assume you are debugging the WebView with Safari you will find the array in the log. If you open the console the values will be read at that time. So you see the final value instead of the one at the time it was printed to the console.

Solution: Use JSON.stringify(arr2) at all times to see the actual value at that point in time.

It would also have worked if you used $log.log("array after assigning: " + arr2), because this would implicitely call arr2.toString(), thus making the value immutable after printing it to the console.

Also see these questions:

Community
  • 1
  • 1
stuikomma
  • 61
  • 7
  • Sorry for that late response. I totally forgot my credentials and found out accidentally that I was using this email as login. The answer was right, I should have used JSON.stringify(). Thanks. – hmoews Jun 28 '16 at 07:53