javascript - 使用 JavaScript 如何使用数组递增字符串来创建循环?

标签 javascript arrays

我正在尝试制作一个网页,每次刷新时其墙纸都会发生变化。我希望它在每次刷新页面时显示数组中的下一张图像。所以每次刷新都会在列表中进行,直到结束,然后重新开始。

现在我正在使用一个数组并使用随机索引访问它,但我需要使用一个每次增加 1 的索引来访问它,一旦我达到数组长度我需要它重新开始...... . 现在我正在使用这个(我花了很长时间才弄明白):

$(function background() {
    var images = [
      "wallpaper1.jpg",
      "wallpaper2.jpg",
      "wallpaper3.jpg",
      "wallpaper4.jpg"
    ];
    $("#hero").css({
      "background-image":
        "url(images/wallpapers/" +

        images[Math.floor(Math.random() * images.length)] 
        
        + ")"
    });
  });

我发现了如何使用这个递增数组中的数字:

var arr = [1,2,3,4];
arr = arr.map(function(val){return ++val;});
console.log(arr);

但我似乎无法获得处理字符串的数字解决方案。我对这一切都是全新的,我正在失去理智:/

最佳答案

您需要将计数器保存到 localStorage您可以在每次加载页面时检索、递增、进行检查,然后再次保存。

$(function () {

    const images = [
      'wallpaper1',
      'wallpaper2',
      'wallpaper3',
      'wallpaper4'
    ];

    // We must check to see if localStorate exists before
    // we do anything
    function hasLocalStorage() {
      try {
        localStorage.setItem('count', 0);
        if (localStorage.getItem('count') === '0') {
          return true;
        }
      } catch(e) {
          return false;
      }
      return false;
    }

    // Fetch the count from localStorage. Because it's
    // saved as a string we need to coerce it to a number
    let count = Number(localStorage.getItem('count'));

    $("#hero").css({
      'background-image': `url(${images[count]})`
    });

    // Increase the count
    count++;

    // If the count is the length of the array (minus one
    // because the array is indexed-based) set the
    // localStorate count to zero, otherwise save the count
    if (count === images.length - 1) {
      localStorage.setItem('count', 0);
    } else {
      localStorage.setItem('count', count);
    }

});

关于javascript - 使用 JavaScript 如何使用数组递增字符串来创建循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68109201/

相关文章:

javascript - 发现在验证方法中按下了哪个提交按钮

c++ - 如何获取用户输入并按变量排序?

javascript - 按索引删除数组元素

java - 为什么会抛出空点异常?

javascript - 如何在 iOS 上取消双击滚动手势?

javascript - 服务中的 Angular 引用错误

javascript - 为什么我不能将两个数组与 "includes"进行比较?

javascript - Electron 将创建者窗口 ID 传递给新的 BrowserWindow

c# - 我如何通过二维数组 'foreach'?

Java读取文本文件中的不同数组