
Question:
I am creating a JSON array exactly as follows (bar using mathrandom).
For example purposes:
var numbers = []; var jsonString = ""; function EveryOneSec() { numbers.push(Math.random()); jsonString = JSON.stringify({'numbers': numbers}); setTimeout(EveryOneSec, 1000); }
When I create the JSON string it will obviously just keep getting bigger.
Is there a way that I can only have the 10 most recently added into the array?
Solution:1
Add the following code to the top of EveryOneSec
if (numbers.length == 10) { numbers.shift(); }
You want to use push
and shift
to ensure you always have the recent 10.
Solution:2
There will be a few ways to handle this, but here is one (Comments added):
Note I took the OP's question very literally. This lets the numbers array continue to grow, but limits the JSON version to only 10 items.
var numbers = []; var jsonString = ""; function EveryOneSec() { numbers.push(Math.random()); // Get total number, minus 10 to get starting index var l = numbers.length - 10; // If l < 10 there are less than ten items, pass 0 to slice. // otherwise pass the starting index to get the last 10 numbers jsonString = JSON.stringify({'numbers': numbers.slice(l < 0 ? 0 : l)}); setTimeout(EveryOneSec, 1000); }
Solution:3
You could dispense with the problem of checking whether the size is ten or not by using
var number = Array(10);
Two downsides you would have to keep a running total of the index i++
instead of using numbers.push
and the JSON string would contain the blank spaces. However, if I remember correctly numbers[numbers.length] =
is supposed to be faster then numbers.push()
. So tracking your index might be faster.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon