1
1
1ss1za2020-04-13 15:13:13
JavaScript
1ss1za, 2020-04-13 15:13:13

Why is the variable only added once to the array?

There are several buttons, when you click on them, you need to place their text in an array.

Why is only one value added? It works if you take the array out of the function, but I have n groups of buttons and each needs its own array

$('.lbl').click(function(){
        const arr = [];
        let txt = $(this).text();
        arr.push(txt);
        console.log(arr);
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Noname, 2020-04-13
@Ddeeeennn

Maybe because it's worth declaring an array outside of a function?
For example like this?

const arr = [];
$('.lbl').click(function(){
        let txt = $(this).text();
        arr.push(txt);
        console.log(arr);
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question