这是我的代码:

var pictures = {};

for (var key in pics) {
    //just interested in the first 3 profile pictures.
    if (i < 3){
        var view = Titanium.UI.createImageView({
            image: pics[key].source,    
            width: 'auto',    
            height: 'auto'
        });

        $.scrollableView.addView(view);

        //store in json object
        pictures['source'] = '[' + pics[key].source + ']';

        i++;
    } else {
        //break out of loop
        break;
    }
}

好的,我知道在JSON中创建JSON数组的语法基本上是这样的:

[ { something, something 2, something 3 }],

如何根据上面的代码动态创建json数组。

pictures['source'] = '[' + pics[key].source + ']';

这只会在列表中存储最后的pics[key].source

===============>>#1 票数:1 已采纳

这是您需要的吗?

var pics = [{ source: 'foo' }, { source: 'bar' }, 
            { source: 'foo' }, { source: 'bar' }];

var pictures = pics.slice(0, 3).map(function(pic, i){
    var ret = {};
    ret[i] = pic.source;
    return ret;
});

console.log(JSON.stringify(pictures)); // [{"0":"foo"},{"1":"bar"},{"2":"foo"}] 

根据评论更新:

var pics = [{ source: 'foo' }, { source: 'bar' }, 
            { source: 'foo' }, { source: 'bar' }];

var imgSources = pics.slice(0, 3).map(function(pic, i){
    return pic.source;
});

console.log({ images: imgSources }); // {"images":["foo","bar","foo"]} 

http://jsfiddle.net/psMSY/

===============>>#2 票数:0

像这样:

var pictures = [];
// your code..........


pictures.push(pics[key].source);

//more code....


var jsonStr = JSON.stringify(pictures);

JSON.stringify

  ask by bobo2000 translate from so

未解决问题?本站智能推荐:

关注微信公众号