开发者

When creating a native JSON array how to limit it to 10 most recent

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?


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.


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜