2

localstorage に 60 個追加したいと考えています。for ループ内で、オブジェクトを作成し、それを文字列に変換して、時間をキーとして localstorage に追加しています。

function populate()
{
    for(var i=0; i < 60; i++)
    {
        var newDate = new Date();
        var card = {
            'name': i,
            'cost': i,
            'type': i,
            'text': i,
            'power': i,
            'toughness': i};    
        localStorage.setItem(newDate.getTime(), JSON.stringify(card));
    }
}

ロジックでは、これが 60 回発生する必要があります。実際には、約 2 ~ 20 回発生し、オブジェクトの属性に与えられる i の値は大きく異なります。11 と 59 の値で 2 を取得することもあれば、1 から 59 または 60 までの数値で 18 を取得することもあります。ランダムのようです。

ここで何が起こっているのですか?

4

2 に答える 2

10

重複する時間の問題が発生しているため、重複は挿入されません。これにより、重複が分離されます。別の実装またはGUIDを選択することもできますが、これはユーザーの裁量に任されています。

function populate()
{
for(var i=0; i < 60; i++)
{
    var newDate = new Date();
    var card = {
        'name': i,
        'cost': i,
        'type': i,
        'text': i,
        'power': i,
        'toughness': i};    
    localStorage.setItem("" + i + newDate.getTime(), JSON.stringify(card));
}
}
于 2012-04-12T21:45:50.237 に答える
0

なぜそれが起こるのかについては、Traviss の答えを参照してください。

function populate()
{
    for(var i=0; i < 60; i++)
    {
        var newDate = new Date();
        var card = {
            'name': i,
            'cost': i,
            'type': i,
            'text': i,
            'power': i,
            'toughness': i};    
        setTimeout(function(){localStorage.setItem(newDate.getTime(), JSON.stringify(card));},1);
    }

}
于 2012-04-12T21:49:02.380 に答える