【问题标题】:Pick random item from array and populate - jQuery从数组中选择随机项并填充 - jQuery
【发布时间】:2014-10-10 09:35:29
【问题描述】:

我想拥有一个包含 10 个不同配方的数组,在每个页面加载时,我想用其中一个配方填充一个 div,我是数组新手,但我不确定为什么这里没有任何警报?

var recipes = [{
    "image": "image1.jpg",
    "ingredients": {
        "a": "eggs",
        "b": "chips"
    },
    "link" : "google.com"
}, {
    "image": "image2.jpg",
     "ingredients": {
        "a": "chocolate",
        "b": "cheese"
    },
    "link" : "msn.com"
}];

var recipe = recipes[0];

alert(recipe);

http://jsfiddle.net/6otvzr1p/1/

【问题讨论】:

  • 我得到[object Object],这是alert在被要求显示JS对象时的正常输出。
  • recipes[0].image 是你想要的 a href 吗?
  • 获取随机数组对象使用var randomRecipe = recipes[Math.floor(Math.random() * recipes.length)];

标签: javascript jquery arrays


【解决方案1】:

实际上你得到的只是正确的值。解析食谱对象并放入所需的值。 您可以使用此代码获取 0 到 9 之间的随机数,该随机数可以作为索引传递给数组

Math.floor((Math.random() * 10))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2020-06-24
    • 2017-06-04
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多