JavaScript Incrementing a number in an array - javascript

I want to increment a value in a array when a link is pressed in JavaScript
i Used the following code
<script type="text/javascript">
var i=0;
var numbers = new Array();
function go(val){
numbers[i]=val;
i++;
alert(numbers[i]);
}
</script>
Called the Function like this
<a href='javascript:go(1)' </a>
but always the alert prompts me 'undefined'

The alert is correct -- before you do your alert, you incremented i. You're looking at the next element after the one you just entered.
After calling the method once, your array looks like this:
numbers[0] = 1;
numbers[1] = undefined;
and i == 1.
After calling it again, the array looks like:
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;
and i == 2.
Hopefully you can see that this method will always alert undefined

That's because you increment "i"
i++;
right before you put up the alert! Thus "i" will alwuays refer to the next array slot to use, not the one you just populated.
You could change the alert to use "i-1"
alert(numbers[i - 1]);

You are setting numbers[0] = 1 and then incrementing i which becomes 1 so alert(numbers[1]) is undefined, because it is undefined.
Do the alert before you increment. Also, use onclick or even better unobtrusively attach the event handlers in JS, not in the HTML.

Yes, it does that because you:
Create a completely empty array, and a pointer at 0.
When the function is called, you set the current pointer value to whatever was passed in...
...and then increment the pointer, so it's now pointing past the end of all the elements.
Now you look at the element in the array that's being pointed at, which has to be undefined because of the way you're managing the i pointer.
What were you hoping for this to do, by the way?

The question doesn't even match the code... or the code doesn't match the question?
"I want to increment a value in a array"
Your code is not incrementing the value, it's incrementing the index!
function go(val){
numbers[i]=val;
i++;
}
(where i is the index of the next undefined array element) is just the same as
numbers.push(val);
and if you need i to equal what will be the index of the next undefined array element then
i = numbers.length;
To increment the value you would have to first have numeric values for some array elements; then your function would need the index of which value to increment
var numbers = [0,0,0,0];
function go(i){
numbers[i]++;
}
// testing
go(1);
go(3);
go(1);
alert(numbers);
will show 0,2,0,1
But if your entire goal is to put a value into a new element on the end of an array then just use .push()
and .length will tell you how many elements there are; there is no need to increment an i

Related

i need to increment a number in a classList template string javascript

hello friends I got a hard one and I'm a bit in a pickle
in my blackjack game I create images(of the cards) and the values come from the .PNG name from a list in an object. what I want to do is be able to create a class on those images to be able to use the classList.contain() method in a other function. it seems to work but the number doesn't increment every time I call the function. All the cards have the same class.
function showCard(activePlayer, card) {
if (activePlayer.score <= 20){
let cardImage = document.createElement("img")
function incrementNumber(number){
number = number++
return number
}
//increment the number of the class
cardImage.classList.add(`images${incrementNumber()}`)
cardImage.src = `images/${card}.png`
document.querySelector(activePlayer["div"]).appendChild(cardImage)
hitSound.play()
}
}
I know i most likely forgot a simple thing but i cannot put my finger on it.
I added a number in the ${incrementNumber(1)} still keeps giving me the same images class for all images. thank you for all you're help!
The ++ (increment) operator can be confusing sometimes.
In your case, you are using it, but you are also assigning its return value back to the number. The easiest solution is not doing that assignment (changing number = number++ for just number++)
It also looks like number should be a global variable, not a parameter passed to the incrementNumber function.
The more interesting part to the problem though, is why the code does not work. This is due to how the ++ operator works. When you place it after a variable name (eg number++) JavaScript will effectively do this:
var temp = number;
number = number + 1;
return temp;
It increments the number variable by 1, but it returns the previous value of the variable. In your case, when assigning the result of number++ back to number, the increment operation will basically be cancelled out.
Also, note that you can place the ++ operator before a variable name (like ++number). This will not return the original value of the variable, instead returning the new (incremented) value.
Add a global variable to your scope named number and set it to one. Then replace number = number++ with number++.

increasing a number inside of a mouseClicked funtion

I have a code where I draw an object when the mouse is clicked using mouseClicked = function(){} and then I need to have a number to show how many objects have been drawn. the problem is that the number won't increase. what do I do?
Rather than declaring and incrementing a global variable - you could set the count as a HTML 5 data attribute on the button and then on clicking the button, get the data attribute value, increment it and update the display and the new count on the button.
Note that data-attributes are always strings - hence the need for the parseInt() method, though if I was being a purist - I would have put the radix in as well, but that defaults to 10 - so no need in this case.
It is always better to avoid global variable when possible and data attributes offer a very conveniant way of storing local data.
Thanks to #Sven.hig for the skeletn code of the solution - which I then modified to my approach.
var res=document.getElementById("res")
var btn=document.getElementById("btn")
btn.addEventListener("click",()=>{
const newCount = parseInt(btn.getAttribute('data-count'))+1;
res.textContent = newCount;
btn.setAttribute('data-count', newCount)
})
<div id="res"></div>
<button id="btn" data-count="0">Draw</button>
Here is a simple example that will give you an idea about how to increment a counter
var res=document.getElementById("res")
var btn=document.getElementById("btn")
var count=1
btn.addEventListener("click",()=>{
res.textContent=count
count++
})
<div id="res"></div>
<button id="btn">Draw</button>
If the count variable is defined inside the mouseClicked function as the title say, you are recreating it in every mouseClick. In this case, you should define it outter the function with value = 0 and, inside the function, sum 1 to that value. Anyway, like the comments say, it's necessary that you include the code to your question to give a better answer.
this is an easy way to counter the clicks on a html document.
let counter = 0;
document.onclick = () => {
counter++;
console.log(counter);
}

Array reloop to remove previous set of array data generated

My file works just fine in the first round of loop when i try to rerun the function again. It shows the previous value of the previous loop when i try to use the value to match and after which it shows the correct value. If i run the function again and again, it keeps holding on to the value of the previous generated random value.
for (var i=0; i<9; i++)
{
var ranD = Math.floor(Math.random()*33);
if (mathStar.indexOf(ranD)== -1) {
mathStar.push(ranD);
item[i].innerHTML = mathStar[i];
}
else {
i--;
}
itemVal[i].value = mathStar[i];
}
Substitute using const and let for var within for loop to avoid creating global variables and --i could have unexpected results within the code where i++ is also used in the foor loop.
Is this the first occurrence of "mathStar"?
If this is the first place you're using mathStar, it means it gets created globally and that usually leads to confusion. In this case, take a look at this.
Looking at just this, it seems that you are not resetting your "mathStar" value. This way, any time you run this loop for the nth time, the values you have added to "mathStar" using mathStar.push(...) also occur in the list of values.

Clearing empty element from array

Hello i am not sure why those empty elements still there even i clear (or clear function does not work guess). Might you guys have a look on this. I am getting this array after add another value into same array.I am asking whats is happening behind not just solving code thank you
this is function when ever i click button it adds 4 into DVALUE array.
if("q"+idcount+"d" == this.id){
DVALUE[dcount++] = 4;
// alert("D ARRAY"+DVALUE.toString());
}
And this is when ever i click revert button it will remove last added number
if ("d" === qwer) {
// alert(""+DVALUE.toString());
DVALUE.pop();
cleararrayD(); // also calling this function to remove empty elements when ever this if occurs
}
And this is cleararrayD Function
function cleararrayD() {
lens = DVALUE.length, i;
for (i = 0; i < lens; i++) DVALUE[i] && DVALUE.push(DVALUE[i]); // copy non-empty values to the end of the array
DVALUE.splice(0, lens);
}
I am asking whats is happening behind not just solving code
The .length of DVALUE array does not change at cleararrayD() function call as an element is .push()ed to DVALUE array for each index of DVALUE before .splice() is called with original array .length at second parameter, removing the preceding elements to the elements .push()ed to the array.
Okey i got answer for my question. As you can see it clears array but i put element at wrong indexes. Everytime i click button Dcount++ adding indexes so i just doing this Dcount-- in my removing functions
DVALUE[dcount++] = 4;

getting the size of an array of promises(protractor)

I have a list of checkboxes that I want to check if they are checked. I want to loop through the array of objects and check one by one but I cannot get the size of the array. I have tried the following 2 ways but I get different errors.
var i, n;
networkStatusDetail.detailsList.all(by.tagName('div')).then(function(arr){
console.log(arr.length);
for(i=0;i<; i++){
arr.get(i).element(by.model('displayedsites[site.siteid]')).isSelected().then(function(checked){
expect(checked).toBe(true);
});
}
});
With this code above I get an error saying that arr.get() is not a valid function.
The following code does not work because I am unable to get the size of the array. Assigning the size of the array to another variable only works within a promise function, but once the variable is used outside the value is gone.
networkStatusDetail.detailsList.all(by.tagName('div')).then(function(size){
n = size;
console.log('n = '+n);
});
console.log('n outside '+ n);
for(i=0;i<n; i++){
check.get(i).element(by.model('displayedsites[site.siteid]')).isSelected().then(function(checked){
expect(checked).toBe(true);
// console.log(i);
});
}
the 2 consoles will print 512 and undefined respectively, showing that the value of n outside of the promise function does not work.
I can only make it work if I manually set the max value of the for loop, but this value can change over time so It's not correct.
If anybody could give me a hand on how to do this it would be greatly appreciated.
You don't need to know how many checkboxes are there to loop over them - use map() or each() instead:
element.all(by.model('displayedsites[site.siteid]')).each(function (checkbox) {
return checkbox.isSelected().then(function (isSelected) {
console.log(isSelected);
});
});

Categories

Resources