My code below opens a random website from the array but to stop going on the same website is there a way to delete it once it has been visited. Heres my attempt.
<button onclick="randomLink()";>Click here to go somewhere else!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
var randomLink = function () {
var links = new Array();
links[1] = "http://google.com";
links[2]="http://bing.com";
var max = (links.length)
var randomNumber = Math.floor(Math.random()*max);
var link = links[randomNumber];
links.splice(randomNumber,1);
$('iframe').attr('src', link);
}
</script>
<iframe src="" name="iframe_a" ></iframe>
4 Answers 4
Move links outside of the function:
var links = [
"http://google.com",
"http://bing.com"
];
var randomLink = function() {
var max = links.length;
var randomNumber = Math.floor(Math.random() * max);
var link = links[randomNumber];
links.splice(randomNumber, 1);
$('iframe').attr('src', link);
};
1 Comment
Math.random() * (max-1). You could also just do var link = links.splice(Math.random() * (links.length-1), 1) and remove 4 linesEvery time you call the function, all url's are added to the array. Try to define the array outside the function. To delete something call splice!
best, Sebi
Comments
This is true code, you have ; after "".
<button onclick="randomLink()">Click here to go somewhere else!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
var randomLink = function () {
var links = new Array();
links[1] = "http://google.com";
links[2]="http://bing.com";
var max = (links.length)
var randomNumber = Math.floor(Math.random()*max);
var link = links[randomNumber];
links.splice(randomNumber,1);
$('iframe').attr('src', link);
}
</script>
<iframe src="" name="iframe_a" ></iframe>
1 Comment
You do it using splice for example we have arr :
arr = [1,2,3,4,5,6]
To remove arr[2] which hold the value of 3 we can do :
arr.splice(2,1);
arr will become [1,2,4,5,6]
3 is the previous index of the deleted value and 1 is how many values to delete after that index .
You can read more about splice in MDN .
linksoutside of the function. You're deleting an item usingsplicebut then putting it back when you run the function again.links[0]key and you can have problems. It's better if you don't define the key, it will be asigned automatically by javascriptMath.floor(Math.random()*max)Can give 2 and will work incorrectly