JS: += is returning a weird result - javascript

I asked this question previously and it got redirected (and treated as answered) to this question - "Adding two numbers concatenates them instead of calculating the sum".
But it did not help me solve it, I did try parseInt, Number(), and putting + in front of my number.
So here is my question again, but before I think I need to specify that I am using +=, not just +.
I used this function to add 5 to a number in a p element:
function add5() {lifeTotal.textContent += 5;}
I have a similar function that subtracts 5 to that same number:
function minus5() {lifeTotal.textContent -= 5;}
Now my problem is that while the subtracting function works as expected, the adding one just puts 5 at the right side of the number. So if the number was 10, it would return 105, as if both numbers were actually strings and not numbers... while the subtracting function works normally and treats numbers as numbers...
It turns me crazy. I just learnt this += thing and I really don't think I used it wrong...
So my solution is to instead use ++ five times, like so:
function add5() {lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++;}
It works, but it seems to me this is not the shortest way to write this.
The app I am writing is adding or subtracting by calling the corresponding function with an onclick="function()" in html button tags.
What is happening? What is the shortest way to write this?
Thanks!

Thanks to #aerial301 for this answer:
lifeTotal.textContent = +lifeTotal.textContent + 5
It works. I assume that the + in front of my Var lifeTotal is converting the DOM content targeted by the .textContent to a number, which let JS see 2 numbers instead of a string and the number 5.

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++.

guessing random numbers

I am trying to code a simple function in JavaScript which generate random values in (0,10) and asks the user to guess these numbers. Since I am new with JavaScript I wrote this code which not working. So I need your help to figure out how can I fix it.
Your last if statement in Guessing checks whether the counter is below 5. Remove that statement and you are good to go. Since counter is defined as a global variable, it is increased in the guessGame function even without you giving it as parameter and once it's =5 your code stops executing.
A tip if you are new to programming in general: If your code stops working at a magic value,(5 in this case), it's always a good idea to search it in your code with ctrl+f.
Edit after comment:
You are thinking readInput as a blocking function, it's not. Your do...while function executes readInput every time, and reads the same value from the input box and processes it as wrong. To fix it, remove your Guessing function, put readInput in your html, and at the end of your readInput add the guessGame function where you do your comparison with the random numbers. Try with 1 number first.
Fun fact: Even guessing supposed to work as you intended, it would generate a new set of random numbers at each click, thus make the game much harder.
With 1 number, your code is like this :
html:
Guess : <input type="text" id="nb"/> <input type="button" value="Check" onclick="readInput()"/>
javascript:
var ranval=generateRandom();
var counter=0;
function readInput(){
var input = parseInt(document.getElementById('nb').value);
if (counter<5){
guessGame(input);
}
counter++;
if (counter==5){
console.log("you lost")
}
}
function generateRandom(){
//the 3 random values to be used later
rand1 = Math.floor(Math.random() * 10) ;
ranval=rand1;
}
function guessGame(input){
if (ranval==input){
console.log("correct")
}
}

How to swap two numbers using javascript function with one parameter

My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.
function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed
I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!
Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.

Issue with Javascript < operator returning false when condition is definitely true [duplicate]

This question already has answers here:
Why does less than not work?
(4 answers)
Closed 6 years ago.
I am having an issue with javascript, which I am using as part of a search results page, hopefully someone can help. I have a function that checks to see that the variable 'currentAmount' is less than the variable 'total'. If currentAmount is less than total, then do something, otherwise do nothing.
var currentAmount = document.getElementById('currentAmountHidField').value;
var total = '#Html.Raw(Json.Encode(Model.ResultCount))';
var tempScrollTop = $(window).scrollTop();
function loadMore() {
alert("current amount" + currentAmount);
alert("total" + total);
var listView = $("#propertyList").data("kendoListView");
if (currentAmount < total) {
alert("function is being run");
currentAmount = +currentAmount + 12;
document.getElementById('currentAmountHidField').value = currentAmount;
if (currentAmount >= total) {
$('#loadMoreButton').hide();
}
}
else {
alert("function is not being run");
}
listView.dataSource.pageSize(currentAmount);
listView.refresh();
tempScrollTop = $(window).scrollTop();
}
In the above, currentAmount will always initially be 12. For the most part, this works completely fine but for one instance of the search, where the total = 108, the javascript is processing the else clause of the function. i.e. the alert that says "function is not being run". I can't figure out why.
Note that there are alerts there for testing. It will pop up "currentAmount12" then "total108" then "function is not being run". That doesn't make any sense? I've even tried immediately doing something else with the 2 numbers (e.g subtract 12 from 108) just to check those are being processed as numbers, which they are. And like I say, this is working for every other combination of numbers I've been able to test.
It's like javascript, for one search criteria alone, is reading 12 as more than 108. Interestingly, when I hardcore the value as 12 inside the first line of the loadMore function, it will run as accordingly but obviously that's no good.
Any help at all would be greatly appreciated. Why would javascript think 12 is greater than 108?
Thanks
currentAmount and total are both strings, so they're being compared lexicographically, not numerically. '12' is greater than '108'.
Use parseInt() to convert the input value to a number, and leave out the quotes around total so it will be a number.
var currentAmount = parseInt(document.getElementById('currentAmountHidField').value, 10);
var total = #Html.Raw(Json.Encode(Model.ResultCount));
You obviously knew this was an issue when you wrote:
currentAmount = +currentAmount + 12;
since the + before currentAmount is for converting it to a number (so you get addition insteadof concatenation). I guess you didn't know that it also affects comparisons.
All values that you get from Form controls are strings, and so that is what your currentAmount contains. Then suddenly it should make sense that e.g. "12" < "5", because a "1" is less than a "5".
Solution: use parseInt() or parseFloat() to get actual numbers in your variables, and not strings-that-resemble-numbers-but-arent.
kindly parse your String variables to your desired types: parseFloat/ parseInt
function loadMore() {
currentAmount = parseInt(currentAmount);
total = parseInt(currentAmount);
...
}

understanding Javascript recursion

I am trying to wrap my head around recursive functions, and I do not understand the output (this example is from John Resig's 'Javascript Ninja' book):
var ninja = {
chirp: function chirp(n) {
return (n > 1) ? chirp(n-1) + "-chirp"+n : "chirp"+n;
}
}
$('#hello').html(ninja.chirp(8));
and the output:
chirp1-chirp2-chirp3-chirp4-chirp5-chirp6-chirp7-chirp8
Why is the output of n increasing instead of decreasing? It seems to me that the output would count down from 8 instead of up from 1.
http://jsfiddle.net/9xq7j6y8/1/
If you call chirp(1) the result will be "chirp1".
If you call chirp(2) the result will be chirp(1) + "-chirp2", i.e. "chirp1-chirp2".
If you call chirp(3) the result will be chirp(2) + "-chirp3", i.e. "chirp1-chirp2-chirp3".
As you see, the function calls itself to get the output for the lower numbers, and adds the highest number last.
It is counting down from 8, but the output is getting appended to the beginning of the string, and then you're reading the output from left to right.
If you saw the output as it was being built, it would look like:
-chirp8
-chirp7-chirp8
-chirp6-chirp7-chirp8
...
chirp1-chirp2-chirp3-chirp4-chirp5-chirp6-chirp7-chirp8
Since you only see the final output, it shows up in ascending order.

Categories

Resources