How can I create a loop or function that will display a new array index on every click. I tried using a for loop but I keep getting only the first value and then when I'll click it'll jump to the last value.
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
function textForward (){
arrow.addEventListener('click', function(){
var arr = [
'a','b','c','d'
]
for (var i = 0; i < arr.length; i++)
para.innerHTML = arr[i]
});
}
Each time a button is clicked, the above needs to display the next value of that array in order. (for example, the array will start out at a, then when the user clicks it'll go to b, then on the next click c and so on).
Figured it out, I feel dumb for not figuring this out..Here is the updated code
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
let counter = 0;
function textForward (){
var arr = [
'How are you?',
'Are you Ready to play the Game',
'Here is how it works',
'you have three hints to guess what I am thinking',
'Guess wrong and you are out',
'simple..let the games begin'
]
para.innerHTML = arr[counter];
counter ++;
}
textForward();
You need a global counter to track the current index. Something like this
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
// The current index
var index = 0;
var arr = ['a','b','c','d'];
arrow.addEventListener('click', function(){
para.innerHTML = arr[index];
if(index < arr.length - 1) index++;
});
Related
So I'm making a simulation of the lottery. I generate 6 numbers between 0 and 40 and show them in the html id 'generated'. My problem is that if I click a second time on 'generate' (in my html page), the previous generated numbers are still a part of the array and still show up. Does anybody know how to clear the array when pushed on the button multiple times?
This is my Javascript code:
'use strict';
function generatenumbers(){
let number = [];
let i;
i=0;
for(i= 0; i <= 5; i++){
number[i] = Math.floor(Math.random()*40);
}
i = 0;
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let textnode = document.createTextNode(number[i]);
node.appendChild(textnode);
document.getElementById("generated").appendChild(node);
}
}
You are supposed to remove the previously appended children then add new ones.
var list = document.getElementById("generated");
list.removeChild(list.childNodes[0]); // for removing first child only
//for removing all children
var list = document.getElementById("genrated");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
you don't want to clear the array...you want to clear the document.getElementById("generated") element before you call the loop, that way, there will always be 6 LI elements at the end of the function.
document.getElementById("generated").innerHTML = ""; // clear the element
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let textnode = document.createTextNode(number[i]);
node.appendChild(textnode);
document.getElementById("generated").appendChild(node);
}
I am trying to run a replace text function on my slides based on an two arrays; the first array is the values that are to be replaced and the second array are the values that the corresponding values in the first array should be replaced with.
I.e. the first value in the first array should be replaced by the first value in the second array.
This is my attempt at doing it
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value2','new value 3'];
for (i = 0, s = 0, x = 0; i < currentPresentationSlide.length, s < array1.length, x < array2.length; i++, s++, x++) {
currentPresentationSlide[i].replaceAllText(array1[s],array2[x])
}
}
What further complicates it is, that the replaceAllText will only run on a single page and not the entire presentation, hence it will have to be run as a loop on each individual page in the slide (which is the reason for the loop with the i variable.
Does anyone know what I am doing wrong, cause this is not working for me
Thanks to Rup in the comments i solved it. Just in case anyone has the same issue this is my solution:
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value 2','new value 3'];
for (i = 0; i < currentPresentationSlide.length; i++) {
for (s = 0; s < array1.length; s++)
currentPresentationSlide[i].replaceAllText(array1[s],array2[s])
}
}
I have this code and every time that the first for loop starts again I want it to reset the array to blank as it is using a new user, but I get an out put with all the values in one array.
var items = [];
for (var i = 0; i < userArray.length; i++) {
items.length = 0;
for (var i2 = 0; i2 < test.length; i2++) {
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryUserFav = new Parse.Query(UserFavourite);
queryUserFav.equalTo('item', test[i2].get('item'));
queryUserFav.equalTo('school', test[i2].get('school'));
queryUserFav.equalTo('user1', userArray[i])
queryUserFav.find().then(function(res) {
for (var i3 = 0; i3 < res.length; i3++){
var item = res[i3];
var itemName = item.get('item');
items.push(itemName);
if (items !== []) {
console.log(items.toString()+" + ")
}
}
});
}
}
userArray.length is equal to 2 and test.length is equal to 20. If you were wondering. And when it get to the first for loop I want the array to be set back to blank but it isn't?
Thanks for the help in advance.
I thnk you should use set this:
items.length = 0
because items = []
creates a new array which is not the same.
Also add some promises to make the async requests wait
Have you tried:
items.length = 0;
instead of:
items = [];
Can you please concatenate a "+" to the items variable in console log, like so:
console.log(items.toString()+" + ");
Just for debugging purposes to see if the array is actually being cleared or not. I believe it already might be cleared.
Your issue is that you're executing a loop and triggering async code.
Your loop will completely finish before the first bit of async code is executed:
i == 0
reset items
loop over test (20 items)
queue up a find() with async success handler
i == 1
reset items
loop over test (20 items)
queue up a find() with async success handler
... some time later when find() calls finish ...
call each async block using the items array
Unless there's some other code you're not showing that needs to access the items array, just create it inside your success handler instead:
queryUserFav.find().then(function(res) {
// create array here:
var items = [];
for (var i3 = 0; i3 < res.length; i3++){
var item = res[i3];
var itemName = item.get('item');
items.push(itemName);
if (items !== []) {
console.log(items.toString()+" + ")
}
}
});
I'm am working on a script to count the number of times a certain string (in this case, coordinates) occur in a string. I currently have the following:
if (game_data.mode == "incomings") {
var table = document.getElementById("incomings_table");
var rows = table.getElementsByTagName("tr");
var headers = rows[0].getElementsByTagName("th");
var allcoord = new Array(rows.length);
for (i = 1; i < rows.length - 1; i++) {
cells = rows[i].getElementsByTagName("td");
var contents = (cells[1].textContent);
contents = contents.split(/\(/);
contents = contents[contents.length - 1].split(/\)/)[0];
allcoord[i - 1] = contents
}}
So now I have my variable allcoords. If I alert this, it looks like this (depending on the number of coordinates there are on the page):
584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519,,
My goal is that, for each coordinate, it saves how many times that coordinate occurs on the page. I can't seem to figure out how to do so though, so any help would be much appreciated.
you can use regular expression like this
"124682895579215".match(/2/g).length;
It will give you the count of expression
So you can pick say first co-ordinate 584 while iterating then you can use the regular expression to check the count
and just additional information
You can use indexOf to check if string present
I would not handle this as strings. Like, the table, is an array of arrays and those strings you're looking for, are in fact coordinates. Soooo... I made a fiddle, but let's look at the code first.
// Let's have a type for the coordinates
function Coords(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
return this;
}
// So that we can extend the type as we need
Coords.prototype.CountMatches = function(arr){
// Counts how many times the given Coordinates occur in the given array
var count = 0;
for(var i = 0; i < arr.length; i++){
if (this.x === arr[i].x && this.y === arr[i].y) count++;
}
return count;
};
// Also, since we decided to handle coordinates
// let's have a method to convert a string to Coords.
String.prototype.ToCoords = function () {
var matches = this.match(/[(]{1}(\d+)[|]{1}(\d+)[)]{1}/);
var nums = [];
for (var i = 1; i < matches.length; i++) {
nums.push(matches[i]);
}
return new Coords(nums[0], nums[1]);
};
// Now that we have our types set, let's have an array to store all the coords
var allCoords = [];
// And some fake data for the 'table'
var rows = [
{ td: '04.shovel (633|455) C46' },
{ td: 'Fruits kata misdragingen (590|519)' },
{ td: 'monster magnet (665|506) C56' },
{ td: 'slayer (660|496) C46' },
{ td: 'Fruits kata misdragingen (590|517)' }
];
// Just like you did, we loop through the 'table'
for (var i = 0; i < rows.length; i++) {
var td = rows[i].td; //<-this would be your td text content
// Once we get the string from first td, we use String.prototype.ToCoords
// to convert it to type Coords
allCoords.push(td.ToCoords());
}
// Now we have all the data set up, so let's have one test coordinate
var testCoords = new Coords(660, 496);
// And we use the Coords.prototype.CountMatches on the allCoords array to get the count
var count = testCoords.CountMatches(allCoords);
// count = 1, since slayer is in there
Use the .indexOf() method and count every time it does not return -1, and on each increment pass the previous index value +1 as the new start parameter.
You can use the split method.
string.split('517,594').length-1 would return 2
(where string is '584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519')
Here's my code:
function listDesserts (){
var dessertList = ["pudding", "cake", "toffee", "ice cream", "fudge", "nutella"];
var i = 0;
while (i< dessertList.length){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' +i;
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i];
ul.appendChild(nli);
i++;
}
}
Since I'm setting the li tags IDs based on the number items in my array, i sets it to zero as it should. Rather I want to modify i so that it sets the IDs beginning with 1 without it skipping the first array member. I've tried a few things but I'm missing this. Anybody?
As you are iterating an array, the counter variable should always run from 0 to length-1. Other solutions were possible, but are counter-intuitive.
If you have some one-based numberings in that array, just use i+1 where you need it; in your case 'item-'+(i+1).
Btw, you might just use a for-loop instead of while.
Use var i = 1;
and use i-1 where you currently have i
var i = 1;
while (i< dessertList.length-1){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' + (i-1); //<----- here
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i-1]; //<----- and here
ul.appendChild(nli);
i++;
}