Vecta
Vecta

Reputation: 2350

Splice confusion

I've been going through the rot.js tutorial located here and I'm making sense of the majority of the examples.

However, I'm confused by one line of code and I was hoping someone could explain what's going on.

This is in the Game._generateBoxes function toward the bottom of the page:

var key = freeCells.splice(index, 1)[0];

I understand that it's removing one element from location index from the freeCells array and assigning it to key. I don't understand what the [0] is doing at the end. I tried removing it and it appeared to function normally. What is this accomplishing?

Upvotes: 0

Views: 61

Answers (1)

Quentin
Quentin

Reputation: 943561

var key = freeCells.splice(index, 1);

… assigns an array with one member to key.

var key = freeCells.splice(index, 1)[0];

… assigns the value of the member of the aforementioned array and then discards the array.

var index = 1;

function one () {
  var freeCells = ['a', 'b', 'c']
  var key = freeCells.splice(index, 1)[0];
  alert(typeof key);
}

function two () {
  var freeCells = ['a', 'b', 'c']
  var key = freeCells.splice(index, 1);
  alert(typeof key);
}

one(); two();

Upvotes: 2

Related Questions