Skip to content

Clarification of array example #2491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<script>
let numbers = [1, 2, 3, 4];

function addNumber() {
numbers.push(numbers.length + 1);
function addNumber(value) {
numbers.push(value);
}

$: sum = numbers.reduce((t, n) => t + n, 0);
Expand All @@ -12,4 +12,4 @@

<button on:click={addNumber}>
Add a number
</button>
</button>
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<script>
let numbers = [1, 2, 3, 4];

function addNumber() {
numbers = [...numbers, numbers.length + 1];
function addNumber(value) {
numbers = [...numbers, value];
}

$: sum = numbers.reduce((t, n) => t + n, 0);
Expand All @@ -12,4 +12,4 @@

<button on:click={addNumber}>
Add a number
</button>
</button>
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ Because Svelte's reactivity is triggered by assignments, using array methods lik
One way to fix that is to add an assignment that would otherwise be redundant:

```js
function addNumber() {
numbers.push(numbers.length + 1);
function addNumber(value) {
numbers.push(value);
numbers = numbers;
}
```

But there's a more *idiomatic* solution:

```js
function addNumber() {
numbers = [...numbers, numbers.length + 1];
function addNumber(value) {
numbers = [...numbers, value];
}
```

Expand Down