I’m studying svelte.
the tutorial states that responsiveness is based on assignment and consequently operations with array such as array.push()
must have an assignment.
array.push()
can be converted to numbers = [...numbers, numbers.length + 1]
.
How to convert pop, shift, unshift, splice and other similar operation?
Advertisement
Answer
Unshift is the easiest, just use the reverse construction of the push
JavaScript
x
3
1
let arr = [1,2,3,4]
2
arr = [0, arr]
3
Shift can be rewritten using array destructuring, taking the first element and then spreading the rest back into the array-
JavaScript
1
3
1
let arr = [1,2,3,4];
2
[first, arr] = arr;
3
For pop
and splice
there is not really a shortcut you can follow, but you can always just reassign after doing the operation:
JavaScript
1
3
1
arr.pop()
2
arr = arr
3