简体   繁体   English

我如何修改它以使用数组中的所有项目?

[英]How can I revise this to use all of the items in an array?

Here is the code in a function I'm trying to revise. 这是我要修改的函数中的代码。 This example works on a single item from an existing array named "stream": 此示例适用于名为“ stream”的现有数组中的单个项目:

list = [
    {
        service: 'service1',
        user: stream [0],
        template: {
            posted:HTML1 +  stream[0] + HTML2
        }
    }
],

The code originally called for manual entry for the user value so I switched to an array since I use the same value(s) elsewhere with $.each for HTML stuff). 该代码最初要求手动输入user值,所以我切换到数组,因为我在$ .each中使用相同的值作为HTML东西。

The stream array can vary in length so I want to avoid manually writing something like this below since I suspect it would need to match the count of stream items (could be anywhere from 1 to 50 or more): stream数组的长度可以有所不同,因此我想避免手动在下面编写类似的内容,因为我怀疑它需要与stream项目的数量匹配(可以为1到50或更多):

list = [
    {
        service: 'service1', 
        user: stream [0], 
        template: { 
            posted:HTML1 +  stream[0] + HTML2
        }
    }, 
    { 
        service: 'service1', 
        user: stream [1], 
        template: { 
            posted:HTML1 +  stream[1] + HTML2
        }
    } 
],

Thanks for your help and guidance! 感谢您的帮助和指导!

PS This is another attempt at this question and hope it is clearer this time. PS:这是对此问题的另一种尝试,希望这次更加明确。 Still learning. 还在学习。

I believe, you want this: 我相信,您想要这样:

var SERVICE = 'service1';

list = jQuery.map(stream, function (item) { 
  return {
    service: SERVICE, 
    user: item, 
    template: { 
        posted:HTML1 +  item + HTML2
    }
  }; 
});

A solution with just javascript: see Engineer's post for a (simpler) jQuery solution 仅使用javascript的解决方案:有关(更简单的)jQuery解决方案的信息,请参阅工程师的帖子

var list = [];

for (var i = 0; i < stream.length; i++) {
    list.push({
        service: 'service1',
        user: stream[i],
        template: {
            posted: HTML1 + stream[i] + HTML2
        }
    });
}

Have a look at this: http://jsfiddle.net/xHfDb/ 看看这个: http : //jsfiddle.net/xHfDb/

$.map(stream, function(item, index) {
        return {
            service: 'service' + index,
            user: item,
            template: {
                posted: HTML1 + item + HTML2
            }
        }
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM