0

enter image description here I am modifying a HTML5 app that records time time spent on project, date and project code. It uses localstorage and there are two kinds of keys in the localstorage - timestamp keys and one other key called 'userdetails'. The code below lists all data in storage. I would like to list only timestamped data eand not the data contained in key 'userdetails'.

function getAllItems() {
var timeLog = "";
var i = 0;
var logLength = localStorage.length-1;
var totalHours = 0.0;   

for (i = 0; i <= logLength; i++) {
    var itemKey = localStorage.key(i);
    var values = localStorage.getItem(itemKey);
    values = values.split(";");
    var code = values[0];
    var hours = values[1];
    var date = values[2];
4

2 回答 2

1

function getAllItems() {
    var timeLog = "";
    var i = 0;
    var logLength = localStorage.length-1;
    var totalHours = 0.0;   
    for (i = 0; i <= logLength; i++) {
        var itemKey = localStorage.key(i);
        if(itemKey == 'timestamped' ){
        var values = localStorage.getItem(itemKey);
        values = values.split(";");
        var code = values[0];
        var hours = values[1];
        var date = values[2];
      }

    }
}

于 2013-10-25T13:20:33.227 回答
0

这将吐出除userDetails之外的所有键:

function getAllItems() {
    // housekeeping
    var timeLog = ""
        , i = 0
        , logLength = localStorage.length-1
        , totalHours = 0.0
        , theKeyToIgnore = 'userDetails'
    ;   

    // loop through all keys
    for( i = 0; i <= logLength; i++ ) {
        var itemKey = localStorage.key( i )
            , values = localStorage.getItem( itemKey )
        ;

        // is this the ignored key? then skip a loop iteration 
        if( itemKey === theKeyToIgnore ) { continue; }

        values = values.split( ";" );

        // set our data
        var code    = values[ 0 ]
            , hours = values[ 1 ]
            , date  = values[ 2 ]
        ;

        // display it
        console.log( itemKey + ' => ' + code + ' ' + hours + ' ' + date );

        // tally total hours
        totalHours += parseFloat( hours ); 
    }

    // display total hours
    console.log( 'total hours: ' + totalHours );
}


> getAllItems();
  1382614467062 => 100 7 10/01/2013
  1382614476654 => 200 3 10/02/2013
  1382703706453 => 123 6 10/16/2013
  total hours: 16
于 2017-07-17T18:11:06.677 回答