0

オブジェクトの配列にオブジェクトを簡単に追加できるように、background.js に pushLocalStorage() という独自のメソッドを作成しました。その目的は、単純に呼び出し元からデータを取得し、キーが存在する場合は、データ オブジェクトを前の反復で格納された既存の配列にプッシュすることです。キーが存在しない場合は、新しい配列インデックスを作成します。

最初のオブジェクトの作成は正常に機能します。2 番目の挿入は正常に完了しましたが、オブジェクトではなく配列の長さが挿入されました。最後に、データが配列ではなく文字列であり、データを挿入する前にデータが配列であることをコードが検証するため、3 回目以降の挿入は失敗します。コードの後のロギングの例を参照してください。

これが私のコードです:

else if (request.method == 'pushLocalStorage')      
{
    var key; 
    var data;
    var stored;

    // if key isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Key value was not sent from caller.'});
    }

    // if the key isn't a string type then quit with error.
    if ( 'string' != typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Expected key passed from caller to be a ' + 
                                        'string but it was a(n) ' + typeof(request.key) + ' instead'});
    }

    // if data value isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.data) )
    {
        sendResponse({success: 0,error: 'Data value was not sent from caller.'});
    }

    key    = request.key;
    data   = request.data;
    stored = localStorage.getItem(key); // attempt to retrieve existing store named by 'key'

    // Now if stored isn't null or undefined...
    if ( 'undefined' != typeof(stored) && stored != null )
    {
        // parse it back into a valid data structure from JSON
        stored = JSON.parse(stored);

        // if stored exists (should be an Array object)
        if ( stored.length )
        {
            // stored should be an array of objects so...
            for ( var i = 0 ; stored.length < i ; i++ )
            {
                // make sure not to push dupe tickets into the array. In this case, replace
                // the existing ticket with the new.
                if ( data.id === stored[i].id )
                {
                    stored[i] = data;

                    // save the data to localStorage (do not push but overwrite)
                    localStorage.setItem(key,JSON.stringify(stored));
                    test = JSON.parse(localStorage.getItem(key));
                    sendResponse({success: 1,data: test});
                    return;
                }
            }

            // save the stored object back to localStorage after pushing the new data to it.
            localStorage.setItem(key,stored.push(JSON.stringify(data)));
            test = JSON.parse(localStorage.getItem(key));
            sendResponse({success: 1,data: test});
        }
        else
        {
            console.log(' data would be: %o and stored was: %o', data,stored);
            sendResponse({success: 0, error: 'Attempt to coerce object into array not allowed.'});
        }
    }
    else
    {
        console.debug(' Creating new array to be stored.');
        stored = new Array(data);
        stored = JSON.stringify(stored);

        localStorage.setItem(key,stored);

        test = localStorage.getItem(key);
        test = JSON.parse(test);
        console.log('setItem.' + key + ',' + stored + '\nThe stored obj was: %o and the localStored.getItem after storage was: %o',test,localStorage.getItem(key));
        sendResponse({success: 1,data: test});
    }
}

クロムコンソールでは、次のようになります。

Object  
localstorage push! [Object]:  
Object
localstorage push! [Object]:
Object
localstorage push! [Object]:
Object
localstorage push! [Object]:
Object
localstorage push! 2:  
Object
localstorage push! [Object]: 
Object
localstorage push! 2:
Object
localstorage push failed: Attempt to coerce object into array not allowed. 
Object
localstorage push failed: Attempt to coerce object into array not allowed.
Object
localstorage push! [Object]:
Object
localstorage push! 2:
Object
localstorage push failed: Attempt to coerce object into array not allowed.

そのため、私が望む機能をコーディングするいくつかの異なる方法を試した後、何もうまくいかないようです。私は間違ったツリーを吠えていますか、それとも実装が貧弱なコードを書いているだけですか?

ティア

編集:

完了時の修正コード:

if (request.method == 'pushLocalStorage')       
{
    var key; 
    var data;
    var stored;

    // if key isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Key value was not sent from caller.'});
    }

    // if the key isn't a string type then quit with error.
    if ( 'string' != typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Expected key passed from caller to be a ' + 
                                        'string but it was a(n) ' + typeof(request.key) + ' instead'});
    }

    // if data value isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.data) )
    {
        sendResponse({success: 0,error: 'Data value was not sent from caller.'});
    }

    key    = request.key;
    data   = request.data;
    stored = localStorage.getItem(key); // attempt to retrieve existing store named by 'key'

    // Now if stored isn't null or undefined...
    if ( 'undefined' != typeof(stored) && stored != null )
    {
        // parse it back into a valid data structure from JSON
        stored = JSON.parse(stored);

        // if stored exists (should be an Array object)
        if ( stored.length )
        {
            // stored should be an array of objects so...
            for ( var i = 0 ; i < stored.length ; i++ )
            {
                // make sure not to push dupe tickets into the array. In this case, replace
                // the existing ticket with the new.
                if ( data.id === stored[i].id )
                {
                    stored[i] = data;

                    // purge the item...
                    localStorage.removeItem(key);

                    // save the data to localStorage.
                    localStorage.setItem(key,JSON.stringify(stored));

                    data = JSON.parse(localStorage.getItem(key));
                    sendResponse({success: 1,data: data});
                    return;
                }
            }

            // save the stored object back to localStorage after pushing the new data to it.
            stored.push(data);
            localStorage.setItem(key,JSON.stringify(stored));
            data = JSON.parse(localStorage.getItem(key));
            sendResponse({success: 1,data: data});
        }
        else
        {
            sendResponse({success: 0, error: 'Attempt to coerce object into array not allowed.'});
        }
    }
4

1 に答える 1

0

大丈夫。理解した。ジグザグするべきだったときにジグザグしていました。

違う:

localStorage.setItem(key,stored.push(JSON.stringify(data)));

右:

stored.push(data);
localStorage.setItem(key,JSON.stringify(stored));

test = JSON.parse(localStorage.getItem(key));
sendResponse({success: 1,data: test});

問題は、文字列化された値を配列オブジェクトにプッシュしようとしたことでした。ええ、それはできません。それを修正したら、すべてがうまくいきました。

于 2012-07-24T01:08:53.667 に答える