Splice strange thing

55 views Asked by At

I have next code

function doneOrNot(board) {
    console.log(board);
    let blockNum = [...(board.splice(0, 2))];
    return blockNum;
}
console.log(doneOrNot([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))

On first console.log I got

(3) [Array(3), Array(3), Array(3)]
0: (3) [7, 8, 9]
length: 1
[[Prototype]]: Array(0)

(Length 3 or 1???)

And on second:

(2) [Array(3), Array(3)]
0: (3) [1, 2, 3]
1: (3) [4, 5, 6]
length: 2
[[Prototype]]: Array(0)

But why array of arrays have changed before (after?) split?

1

There are 1 answers

1
Siva K V On

Array splice method, mutates original array and returns removed items.

const arr = [1, 2, 3];
// now arr has 3 elements

const removed_items = arr.splice(0, 2);

// Now removed_items will have [1, 2]
// and arr will have [3]

By the time When you expand on 'console log' in dev tools, the arr has only 1 element. That is reason you are seeing the 1 element.