Can you please take a look at this code and let me know why the storage.push(players)
instead of adding new array/set of players
into storage
is merging them with previously added array?
Technically what I am expecting here is getting something like this
[
[2,52,35,16,18,46],
[18,44,66,25,78,26]
]
but what I am getting now is only one array in storage like
[
[2,52,35,16,18,46,18,44,66,25,78,26]
]
var storage = [];
var players = [];
function createplayers(arr) {
for (let i = 0; i < 8; i ) {
let a = true,
n;
while (a) {
n = Math.floor(Math.random() * 100) 1;
a = arr.includes(n);
}
arr.push(n);
}
}
var x = 3;
var interval = 1000;
for (var i = 0; i < x; i ) {
setTimeout(function() {
createplayers(players);
storage.push(players)
console.log(players)
console.log(storage)
}, i * interval)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
Your had only one players
array all the time. Move the array creation to createplayers()
.
var storage = [];
function createplayers() {
var arr = [];
for (let i = 0; i < 8; i ) {
let a = true,
n;
while (a) {
n = Math.floor(Math.random() * 100) 1;
a = arr.includes(n);
}
arr.push(n);
}
return arr;
}
var x = 3;
var interval = 1000;
for (var i = 0; i < x; i ) {
setTimeout(function() {
var players = createplayers();
storage.push(players)
console.log(players)
console.log(storage)
}, i * interval)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
This Question has nothing to do with jQuery
You have to clear the players array everytime you add to storage.
Here is the solution
var storage = [];
var players = [];
function createplayers(arr) {
for (let i = 0; i < 8; i ) {
let a = true,
n;
while (a) {
n = Math.floor(Math.random() * 100) 1;
a = arr.includes(n);
}
arr.push(n);
}
}
var x = 3;
var interval = 1000;
for (var i = 0; i < x; i ) {
setTimeout(function() {
createplayers(players);
storage.push(players)
console.log(players)
//Notice this line
players=[];
console.log(storage)
}, i * interval)
}