遍历数组中的元素和元素

时间:2020-12-05 21:22:13

I want to pick random product objects from an array and place the info that they contain in four different containers. All the containers is hard coded in html and has the same class name, and I want to iterate through them.

我想从数组中选择随机产品对象,并将它们包含的信息放在四个不同的容器中。所有容器都是用html进行硬编码的,并且具有相同的类名,我想迭代它们。

Below you see the code, and that I'm using .each for this task, which of course doesn't work because every time the for loop runs it starts over again.

下面你看到代码,我正在使用.each用于这个任务,当然这不起作用,因为每次for循环运行它都会重新开始。

So, what is the best way to solve this?

那么,解决这个问题的最佳方法是什么?

function AddProducts(products) {

    for(var i = 0; i < 4; i++) {
        var number = Math.floor(Math.random() * products.length);

        $('.product').each(function(index) {
            $(this).find('h3').html(product[number].name);
        });
    }
}

    <div class="row span12">
      <ul class="thumbnails">
        <li class="span3 product">
          <div class="thumbnail padding">
            <h3>Product name</h3>
            <p>Description</p>
          </div>
        </li>
        <li class="span3 product">
          <div class="thumbnail padding">
            <h3>Product name</h3>
            <p>Description</p>
          </div>
        </li>
        <li class="span3 product">
          <div class="thumbnail padding">
            <h3>Product name</h3>
            <p>Description</p>
          </div>
        </li>
        <li class="span3 product">
          <div class="thumbnail padding">
            <h3>Product name</h3>
            <p>Description</p>
          </div>
        </li>
      </ul>
    </div>

3 个解决方案

#1


2  

If you want to pick random products and place them into each container without duplicates, you have to shuffle the array first:

如果你想挑选随机产品并将它们放入每个容器而不重复,你必须首先洗涤数组:

function shuffle(o)
{ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

function AddProducts(products) 
{
    // this function modifies the array in-place
    // make a copy if you need to
    // products = shuffle(products.slice(0));
    shuffle(products);

    $('.product').each(function(i) {
        if (products[i]) {
            $(this).find('h3').html(products[i].name);
        }
    });
}

AddProducts([{name: 'foo'}, {name: 'bar'}, {name: 'baz'}, {name: 'dude'}]);

DEMO

The shuffle() function is taken from this question: How can I shuffle an array?

shuffle()函数取自这个问题:如何对数组进行洗牌?

Also, one of your <li> elements has the wrong class .producer instead of .product. Okay, you've fixed that now :)

此外,您的

  • 元素之一具有错误的类.producer而不是.product。好的,你现在修复了:)

  • #2


    1  

    You don't need the for loop, when already using the jQuery .each() function.

    在使用jQuery .each()函数时,您不需要for循环。

    var productTmp = product.slice(0);
    
    $( '.product' ).each( function( index ) {
    
        var number = Math.floor( Math.random() * productTmp.length );
    
        $( this ).find( 'h3' ).html( productTmp[number].name );
    
        productTmp[number] = undefined;
    
    } );
    

    Instead of copying the original array and deleting the used products, you could use a condition or something, to remember which products of the list already were inserted. This should prevent multiple occurrences of one product in the list (as your are picking them randomly).

    您可以使用条件或其他内容来记住已插入列表的哪些产品,而不是复制原始数组并删除已使用的产品。这应该可以防止列表中出现多个产品(因为您随机选择它们)。

    #3


    1  

    Are you looking for something like this?

    你在找这样的东西吗?

    function AddProducts(products) {
        var selectedProducts = [];
        var producers = $('.producer');
    
        for(var i = 0; i < 4; i++) {
            var number = Math.floor(Math.random() * products.length);
            producers.eq(i).find('h3').html(product[number].name);
        }
    }
    

    #1


    2  

    If you want to pick random products and place them into each container without duplicates, you have to shuffle the array first:

    如果你想挑选随机产品并将它们放入每个容器而不重复,你必须首先洗涤数组:

    function shuffle(o)
    { //v1.0
        for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    };
    
    function AddProducts(products) 
    {
        // this function modifies the array in-place
        // make a copy if you need to
        // products = shuffle(products.slice(0));
        shuffle(products);
    
        $('.product').each(function(i) {
            if (products[i]) {
                $(this).find('h3').html(products[i].name);
            }
        });
    }
    
    AddProducts([{name: 'foo'}, {name: 'bar'}, {name: 'baz'}, {name: 'dude'}]);
    

    DEMO

    The shuffle() function is taken from this question: How can I shuffle an array?

    shuffle()函数取自这个问题:如何对数组进行洗牌?

    Also, one of your <li> elements has the wrong class .producer instead of .product. Okay, you've fixed that now :)

    此外,您的

  • 元素之一具有错误的类.producer而不是.product。好的,你现在修复了:)

  • #2


    1  

    You don't need the for loop, when already using the jQuery .each() function.

    在使用jQuery .each()函数时,您不需要for循环。

    var productTmp = product.slice(0);
    
    $( '.product' ).each( function( index ) {
    
        var number = Math.floor( Math.random() * productTmp.length );
    
        $( this ).find( 'h3' ).html( productTmp[number].name );
    
        productTmp[number] = undefined;
    
    } );
    

    Instead of copying the original array and deleting the used products, you could use a condition or something, to remember which products of the list already were inserted. This should prevent multiple occurrences of one product in the list (as your are picking them randomly).

    您可以使用条件或其他内容来记住已插入列表的哪些产品,而不是复制原始数组并删除已使用的产品。这应该可以防止列表中出现多个产品(因为您随机选择它们)。

    #3


    1  

    Are you looking for something like this?

    你在找这样的东西吗?

    function AddProducts(products) {
        var selectedProducts = [];
        var producers = $('.producer');
    
        for(var i = 0; i < 4; i++) {
            var number = Math.floor(Math.random() * products.length);
            producers.eq(i).find('h3').html(product[number].name);
        }
    }