This question already has an answer here:
localStorage concatenating Integer instead of adding
(1 answer)
Closed 4 years ago.
So Im trying to write my program to where every time the function is activated, the value of 'money' in local storage goes up by 1. When I tested it out, It does go up by 1. But the next time, it went up by 10, then 100. Why? I couldnt find anyone with the same issue. Heres the code:
<script>
function changeText() {
localStorage.setItem("money", localStorage.getItem("money") + 1);
localStorage.setItem("map", true);
}
</script>
localStorage.getItem("money") will return a string, since it stores only string. When adding data to storage, it is implicitly converted to a string.
You can convert the string to number and then do addition and store the value
function changeText() {
if (localStorage.getItem('money') === null) {
localStorage.setItem('money', 1)
} else {
localStorage.setItem("money", +localStorage.getItem("money") + 1)
}
}
Try doing -
<script>
function changeText() {
var money = parseInt(localStorage.getItem("money"));
localStorage.setItem("money", money + 1);
localStorage.setItem("map", true);
}
</script>
parseInt converts string to number so if you pass parseInt("1") it will spit out 1 which will be of type number. Then you can add 1 to the number.
You are alomost there! Like others metioned here, localstorage works with strings and to convert a string to number just use the folowing in your code to return the value as number:
Number(your_string_number)
This should work for you:
<script>
function changeText() {
localStorage.setItem("money", Number(localStorage.getItem("money")) + 1);
localStorage.setItem("map", true);
}
</script>
Related
I'm trying to create a function that will take the user's inputted number and simple add 7 to it in JavaScript. I'm doing this in the console on my Firefox browser. I get the prompt as expected but after that it just displays undefined, I can't understand why. I tried to change the parameter to just the number variable but that didn't work out. Here's my code:
var number =prompt("Pick a number");
function add7(NewNumber){
NewNumber = 7 + number;
return (NewNumber);
}
Try this:
function add7(){
return parseInt(prompt("Pick a number"))+7;
}
add7();
prompt() returns a string so you first have to parse that value.
I have also removed unnecessary assignments from your code.
You should call your function like below.
function add7(number) {
number = number + 7;
console.log(number);
}
add7(3);
You should prompt inside the function, not outside
Also you don't need to pass any parameters to that function:
function add7(){
var number =prompt("Pick a number");
var NewNumber = 7 + parseInt(number);
return (NewNumber);
}
add7();
Convert the string to an integer.
var number =prompt("Pick a number");
function add7(NewNumber){
NewNumber = 7 + parseInt(number);
return (NewNumber);
}
If you paste this example directly into your browser console window, it should give you the desired effect.
var number = prompt("pick a number")
function add7(NewNumber){
NewNumber = 7 + parseInt(number);
return (NewNumber);
}
console.log(add7(number))
I'm a newbie to Javascript so please bear with me for this basic question,
I'm trying to get my function to add all the individual digits in a string together, and then keep doing this until I'm left with a single digit!
3253611569939992595156
113 // result of the above digits all added together
5 //result of 1+1+3
I've created a while loop, but it only adds the numbers together once, it dosn't repeat until a single digit and I can't work out why!
function rootFunc(n) {
var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number
while (splite.length > 1) {
splite = splite.reduce(getSum);
}
return splite;
}
console.log(rootFunc(325361156993999259515));
function getSum(total, num) {
return total + num;
}
You're reducing properly, but what you're not doing is re-splitting. Try breaking this out into separate functions:
function digits(n) {
return n.toString().split('').map(x =>Number(x));
}
Then split each time:
function rootFunc(n) {
var d = digits(n);
while (d.length > 1) {
d = digits(d.reduce(getSum));
}
return d;
}
The problem here is that you return the result after the first splice. You need to have a recursive function. To do this, you can put this before the return :
if(splite > 9) splite = rootFunc(splite);
This way, you check if the result is greater than 10, if not you do the function with the remaining digits
I was looking this over in jsfiddle, and your number isn't being passed to exact precision, so just console logging n as soon as you call rootFunc, you've already lost data. Otherwise, to fix your loop, you need to remap splite to a string before the end of your codeblock since your while statement is checking .length, which needs to be called on a string. Put this piece of code at the end of the block:
splite = splite.toString().split('').map(x =>Number(x));
I have a function:
function splitToDigits(n) {
var digits = ("" + n).split("").map(function(item) {
return parseInt(item, 10);
});
console.log(digits);
}
console.log(splitToDigits(123456784987654321));
This is returning digits = [1,2,3,4,5,6,7,8,4,9,8,7,6,5,4,3,2,0].
Any idea why the last element is 0? I noticed that when I delete 2 elements from the array it acts normally. Thanks for all the great answers! :)
As Jaromanda X mentioned in the comments section above, JavaScript does not have enough precision to keep track of every digit in the integer you passed to your function.
To fix this problem, you should instead pass a string:
console.log(splitToDigits('123456784987654321'))
However, I would also like to point out that you can greatly simplify your splitToDigits method:
function splitToDigits(n) {
return [].map.call(n + '', Number)
}
console.log(splitToDigits('123456784987654321'))
console.log(splitToDigits(1234))
It's because Javascript is truncating numbers.
The best way to see this is by doing this console.log:
function splitToDigits(n) {
console.log(n);
var digits = ("" + n).split("").map(function(item) {
return parseInt(item, 10);
});
}
Then, when you ran: splitToDigits(123456784987654321), you already get 123456784987654320. Hence, it has nothing to do with your code as you have still not processed it.
If you add digits, it changes to scientific notation:
splitToDigits(1234567849876543211521521251) // turns to 1.2345678498765432e+27
It's a Javascript precision issue. That's all :)
I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.
var count = {
digit: 0,
increment: function() {
setInterval(function() {
count.digit++;
}, 500);
if (count == 10) {
count.increment = null;
}
}
};
document.write("The number is " + count.digit);
count.increment();
The result is: "The number is 0" but it does not increment. Why?
"A string" + "another string" == "A new string"
… and a new string is not a live updating version of the combination of the two strings that formed it in the first place.
Even if it was, then document.write takes a string, expresses it as HTML, then adds it to the document — so that wouldn't live update it either.
You would need to use DOM methods to modify the HTML document instead of the string. The WSC has a good introduction to manipulating HTML with DOM: http://dev.opera.com/articles/view/creating-and-modifying-html/
You have another problem in that setting count.interval to null wouldn't stop the function incrementing the counter every half second since:
You aren't overwriting the function that is being called every half second
Replacing a reference to a function with something else, doesn't stop that function from existing unless all references to it are overwritten, and setInterval would maintain the reference.
You need to keep the return value from setInterval and use it to clearInterval.
You need to have your if statement inside the setInterval also count.digit == 0
This is a bit cleaner IMO
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10)
clearInterval(interval);
document.write("The number is " + count.digit);
}, 500);
}
};
count.increment();