简体   繁体   中英

How to print from a random 2 dimensional array

How do I go about printing the Title & Image from the same array?

 var images=[

            ["Title 1", "image1.jpg"],
            ["Title 2", "image2.jpg"]

            ];

            // select an array
            var randomNumber = function(){
            return images[Math.floor(Math.random() * images.length)];
            };

            // display title & image

            $('<img/>').attr("src", randomNumber).appendTo("#div1");
            $('<h1></h1>').attr("id", randomNumber).appendTo("#div2");

With this:

var r = randomNumber();
$('<img/>').attr("src", r[1]).appendTo("#div1");
$('<h1></h1>').text(r[0]).appendTo("#div2");

This solves your problem.

However, I'd refactor all your code to this, to make it more understandable:

var images=[
  {title: "Title 1", src: "image1.jpg"},
  {title: "Title 2", src: "image2.jpg"}
];

var getRandomImage = function(){
  return images[Math.floor(Math.random() * images.length)];
};

// display title & image  
var image = getRandomImage();
$('<img/>').attr("src", image.src).appendTo("#div1");
$('<h1></h1>').text(image.title).appendTo("#div2");

Hope this helps. Cheers

change your code like,

// select random number

function randomNumber(){
            return Math.floor(Math.random() * images.length);
        };

// display title & image

var num = randomNumber();
$('<img/>').attr("src", images[num][0]).appendTo("#div1");
$('<h1></h1>').attr("id", images[num][1]).appendTo("#div2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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