When I write pathfinding codes in JavaScript, I ran into this problem: how to empty the array?
Methods
1
| array.splice(0, array.length)
|
1 2 3
| while (array.length > 0) { array.pop() }
|
Difference between Method 1 and the others
Method 1 only reassign a:
1 2 3 4 5 6 7 8
| let a = [1, 2, 3] let b = a
// empty a, but doesn't affect b a = []
console.log('a =', a) console.log('b =', b)
|
Method 2, 3, 4, will empty multiple variables referencing the same object:
1 2 3 4 5 6 7 8
| let a = [1, 2, 3] let b = a
// empty a and b a.length = 0
console.log('a =', a) console.log('b =', b)
|
More
See https://github.com/UMU618/js-empty-array#example