1

I'm making a project with PebbleJS.

i'm a noob and i'm learning little by little..so after recieving a JSON from a webpage and put all the data in localStorage objects, i want to put my variables in a UI.Menu Window, which is basically a JSON variable as you can see in example below:

var main = new UI.Menu({
sections: [{
  items: [
  {
    title: 'street name a',
    subtitle: 'ID 1121'
  }, {
    title: 'street name b',
    subtitle: 'ID 1431'
  }, {
    title: 'street name c',
    subtitle: 'ID 1907'
  },{
    title: 'street name d',
    subtitle: 'ID 1002'
  },{
    title: 'street name e',
    subtitle: 'ID 1330'
  },

        ]
}]
}); 

i tried to make a loop cycle inside but gives me error...(pseudocode)

for (var x=0;x<10;x++)
  {
    title: localStorage.title+x,
    subtitle: 'ID '+localStorage.title+x
  }

i need to make this with no jQuery or other JS Frameworks, only pure javascript...

4

1 回答 1

1

if i understand you question correctly, you want to create the data-structure from your first code example through a loop.

the data structure is a object with some properties and sub-objects like arrays. the structure just defines objects in your code. there is no json involved.

json is a subset of javascript which is used to interchange data-structures. it consists of plain text files with just javascript object declarations and is usually parsed to create a data-structure in memory. by declaring your data-structure in code there is no need to use an additional json-parsing step.

to setup the initial structure as above you would do:

var data = {
    sections: [
        {
            items: []
        }
    ]
}

than you would get the items array:

var items = data.sections[0].items

to this array you can add the items with your loop:

for ( var x = 0; x < 10; x++ ) {
    var item = {
      title: localStorage.title + x,
      subtitle: 'ID ' + localStorage.title + x
    };

    items.push(item);
}

now you can build your UI.Menu with the data-object.

var main = new UI.Menu(data)
于 2014-08-17T18:59:11.910 回答