I'm trying to display a seperate .png file when the result is from oneArray
and another .png when the result from the randomiser is from twoArray
. The pictures will display their rarity. However, when i duplicate the function displayImage()
bit, it results in nothing? is there another way to do this?
function myFunction() {
var luck = ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
oneArray = ["tree", "dog", "cat", "wood"];
twoArray = ["tiger", "dot", "tame", "buzz"];
lucknumber = Math.floor((Math.random() * luck.length));
if (lucknumber < 8) {
function displayImage() {
var num = Math.floor(Math.random() * oneArray.length);
window.canvas.src = oneArray[num];
}
displayImage();
} else {
function displayImage() {
var num = Math.floor(Math.random() * twoArray.length);
window.canvas.src = twoArray[num];
};
displayImage();
}
}
myFunction();
Thank you - i know there's probably many other questions that match this one but not for the scenario i'm currently in D:
function
are not created at the line it exists in your code. JavaScript scans your code and function
s are created immediately before any of your code is run. There are two ways to fix this.
Assign the function
as variables instead:
var displayImage = function() {
var num = Math.floor(Math.random() * oneArray.length);
window.canvas.src = oneArray[num];
}
When you assign as a variable, the declaration (variable name) is the only thing created at the top. The function itself is not created.
But this isn't the cleanest of solutions. Personally, I would refactor and turn both into one function that is compatible with both:
function displayImage(array) {
var num = Math.floor(Math.random() * array.length);
window.canvas.src = array[num];
}
Just pass it in the array of choice into the same function
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.