简体   繁体   中英

console.log and execution of function with Node.js and CoffeeScript

I compile CoffeeScript with node. In a script I have a function which clears arrays. I want to console.log the empty array. I can't see the difference between the 3 block logs:

clearArray = (arr) ->
  arr.splice 0 , arr.length

#Block 1
arr = [1,2]
clearArray arr
console.log arr

#Block 2
array = [1,2]
console.log clearArray array

#Block 3
console.log clearArray [1,2] 

#Block 1 logs: []
#Block 2 & 3 log: [ 1, 2 ]

In my understanding all Blocks should log "[ ]" and return an empty array, since clearArray returns the result of arr.splice(). It seems like #Block2 &3 do not execute the splice function?! Any help is much appreciated.

Splice() modifies the array in place and returns an array with the elements you remove.

var arr = [1, 2];
var a = arr.splice(0, 2);

console.log(arr);
[] 

console.log(a);
[1, 2]

As Rodrigo says splice returns the initial array, which leads to a missunderstanding caused by Coffee's implicit return statement. Your function is equivalent to this:

clearArray = (arr) ->
  return arr.splice 0 , arr.length

To solve this you have to return the sliced array

clearArray = (arr) ->
  arr.splice 0 , arr.length
  return arr

Wich again is the same as

clearArray = (arr) ->
  arr.splice 0 , arr.length
  arr

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