Stoic Lion
Stoic Lion

Reputation: 480

Svelte's reactivity with array operation

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?

Upvotes: 1

Views: 844

Answers (2)

kockburn
kockburn

Reputation: 17636

It's unfortunate that these methods (pop , shift, unshift, push) don't work, and that's because the system requires the usage of the assignment operator (=) to work properly.

You can use slice and concat to achieve most of the other methods.

// pop
let arr = [1,2,3];
arr = arr.slice(0, -1);
console.log(arr);

// shift
let arr = [1,2,3];
arr = arr.slice(1);
console.log(arr);

// splice
let arr = [1,2,3,4,5,6,7,8,9,10];
// delete number 6 from the list at index 5
const index = 5;
arr = arr.slice(0, index).concat(arr.slice(index + 1));
console.log(arr);

// push
let arr = [1,2,3];
arr = arr.concat([4]);
console.log(arr);

// unshift
let arr = [1,2,3];
arr = [0].concat(arr);
console.log(arr);

Upvotes: 2

Stephane Vanraes
Stephane Vanraes

Reputation: 16451

Unshift is the easiest, just use the reverse construction of the push

let arr = [1,2,3,4]
arr = [0, ...arr]

Shift can be rewritten using array destructuring, taking the first element and then spreading the rest back into the array-

let arr = [1,2,3,4];
[first, ...arr] = arr;

For pop and splice there is not really a shortcut you can follow, but you can always just reassign after doing the operation:

arr.pop()
arr = arr

Upvotes: 3

Related Questions