【问题标题】:Disable array if has value in javascript如果在 javascript 中有值,则禁用数组
【发布时间】:2020-06-20 05:45:40
【问题描述】:

我正在尝试使用 javascript 开发一个简单的横幅旋转。

如何确保只有值为 "active": 1 的数组包含在随机播放中?

<div id="ad-container"></div>
<script>
var banner = [{
        "img": "https://DOMAIN.TLD/IMG.JPG",
        "url": "https://LINK.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      },
      {
        "img": "https://DOMAIN.TLD/IMG2.JPG",
        "url": "https://LINK2.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 0
      }
,
      {
        "img": "https://DOMAIN.TLD/IMG3.JPG",
        "url": "https://LINK3.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      }
    ];

function shuffle(banners) {
      var j, x, i;
      for (i = banners.length - 1; i > 0; i--) {

        j = Math.floor(Math.random() * (i + 1));
        x = banners[i];
        banners[i] = banners[j];
        banners[j] = x;
      }
      return banners;
    }

    shuffle(banner);

document.getElementById('ad-container').innerHTML = '<a href="' + banner[0]["url"] + '"><img src="' + banner[0]["img"] + '" style="width: 100%;height: auto;max-width: ' + banner[0]["maxWidth"] + 'px;"></a>';

</script>

所有值为 "active": 0 的数组不应包含在随机播放中。

如果同一页面上包含更多 document.getElementById,也许有人知道如何改进 shuffle/code 或如何防止相同的横幅在页面上显示多次。

提前致谢。

【问题讨论】:

  • 在旁注中,您的 json 在 maxWidth 之后缺少一些逗号

标签: javascript html ads shuffle banner


【解决方案1】:

只过滤数组。

var banner = [{
        "img": "https://DOMAIN.TLD/IMG.JPG",
        "url": "https://LINK.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      },
      {
        "img": "https://DOMAIN.TLD/IMG2.JPG",
        "url": "https://LINK2.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 0
      }
,
      {
        "img": "https://DOMAIN.TLD/IMG3.JPG",
        "url": "https://LINK3.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      }
    ];
    
    let activeParts = banner.filter( info => info.active );
    
    console.log( activeParts ); 

    // do whatever, e.g.:
    // shuffle( activeParts );

【讨论】:

    【解决方案2】:
    banner = banner.map( value => {
       if( value.active === 1 ){
          return value
       }
    });
    

    这将缩小您的数组以仅包含数组中的活动对象。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2020-04-06
    • 2019-09-15
    相关资源
    最近更新 更多