JavaScript if Statement .length not working. Why? - javascript

I have this if statement i have came up with here:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.length==2) {
Orbs+=1;
}
What this code is supposed to do is if the the "TotalMoney" value digit length equals 2,
example (the number 10 has 2 digits)
then it will add 1 "Orb" to the "Orbs" value. Currently, it does nothing. There is HTML and CSS linked to this code but i figured the problem is in this code as it works fine for everything else. Please fix it as i have been trying for hours. Thanks!
For my second question that i just found out with this code here:
var totalMoney=0;
var orbs=0;
if (totalMoney.toString().length==2) {
orbs+=1;
}
This works on getting the number value digits as 2 digits long. The problem now is that once it reaches 10, every time that number goes up (10-99) all the way up, it will add 1 orb each time. I only want it to add 1 orb only when it gets to the 2 digit number (10) and stops adding 1 orb after it reaches it. How can i achieve this? Thanks!

TotalMoney is a number, so it doesn't have a length property. You can check the length of the number by first converting to a string: TotalMoney.toString().length.

Number object in js has no length property, so TotalMoney.length return undefined.
If you want count digits you may use this:
if (TotalMoney.toString().length == 2) {
Orbs+=1;
}
But if TotalMoney will be negative, -1 for exmple, Orbs wil be incremented.
I think there are better way to find all 2-digits number:
if (TotalMoney>9 && TotalMoney<100) {
Orbs+=1;
}

TotalMoney is numeric
so to find its length use this code
TotalMoney.toString().length;
Instead of
TotalMoney.length;
so try to modify your code as below:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.toString().length==2) {
Orbs+=1;
}

Length is property of array & string.It can not be applied on other variables.
If you want to count number of digits you can do
if(TotalMoney>9)
Or you can convert it to string then check it's length
if(TotalMoney.toSting().length>2)

here are some ideas and general comments on your code.
// recommended to start with lower case. upper case such as 'TotalMoney'
// is stylistically reserved for constructors.
var totalMoney=0;
// again - changing form Orbs to orbs;
var orbs=0;
// recommended to use '===' until you are more experienced with JavaScript and
// know about the 'gotchas' that '==' might produce.
// you will be able to check the length of totalMoney only after converting it to a string.
if (totalMoney.toString().length === 2) {
orbs+=1;
}
Finally, totalMoney of 0 will not add one to orbs. But totalMoney of 10, as you mentioned, will.

Related

Correctly format a whole number to a 2 decimal places output in JS but put 0 in front [duplicate]

I have a script which returns a price for a product. However, the price may or may not include trailing zeros, so sometimes I might have 258.22 and other times I might have 258.2. In the latter case, I need to add the trailing zero. How would I go about doing this?
You can use javascript's toFixed method (source), you don't need jQuery. Example:
var number = 258.2;
var rounded = number.toFixed(2); // rounded = 258.20
Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:
function pad(value, width, padchar) {
while (value.length < width) {
value += padchar;
}
return value;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.

Incrementing ID again from last row google apps script

last week I asked something here Increment ID from last row google apps script
Everything was working well but then again, when I used WP1-1000 as a starting row, the result is still appearing as WP1-0NaN
var riskid = mysheet.getRange(rlast,2).getValue();
if (riskid.length > 3){
// Extract number ex. 3
var riskidnb = parseInt(riskid.substring(1,riskid.length));
// Increase risk number +1
riskidnb++
// Convert to string "0004"
var s = "000" + riskidnb.toString();
// Write risk nb i.e. "R004"
mysheet.getRange(r,2).setValue("WP1-"+ s.substring(s.length-4))
}
I tried changing/increasing/decreasing the riskid.length, var s, and s.length-4 from the code but still no avail. The result still appears as "WP1-0NaN"
From my question, the string is already inverted into an integer, but it still appears as NaN when I changed it to WP1.
Also, it seems the code from my last question only workds if there is only 1 letter like in the solution.
I literally tried everything for 2 hours and going mad now.
Explanation / Issue:
That is because in your previous question, the id has the structure
of R-002 but now you are using 3 letters before the -:
WP1-1000. You can now use 4 instead of 1 and it will work:
parseInt(riskid.substring(4,riskid.length));
However, a more generic approach would be to substring after -, therefore you can use indexOf to find that position:
parseInt(riskid.substring(riskid.indexOf('-')+1,riskid.length));
You can apply the same logic for the last line. Instead of hardcopying WP1- you can just get the text before and including -:
riskid.substring(0,riskid.indexOf('-')+1);
Solution:
var riskid = mysheet.getRange(rlast,2).getValue();
if (riskid.length > 3){
// Extract number ex. 3
var riskidnb = parseInt(riskid.substring(riskid.indexOf('-')+1,riskid.length));
// Increase risk number +1
riskidnb++
// Convert to string "0004"
var s = "000" + riskidnb.toString();
// Write risk nb i.e. "R004"
var start = riskid.substring(0,riskid.indexOf('-')+1);
mysheet.getRange(r,2).setValue(start + s.substring(s.length-4))
}

Using # to mark end of array

I am currently studying another user’s code for a coding question from LeetCode. My question is about certain aspects of his code. Here’s a link to the question.
Question:
Why does this user use a # to mark the end of the array?
Under the second if case, the user writes:
ans.push(nums[t] + '->' + (nums[i-1]))
Now, I understand what this statement does. My question is: Why does this produce an output of ["0->2",...] instead of [0"->"2,...]?
var summaryRanges = function(nums) {
var t = 0
var ans = []
nums.push('#')
for(var i=1;i<nums.length;i++)
if(nums[i]-nums[t] !== i-t){
if(i-t>1)
ans.push(nums[t]+'->'+(nums[i-1]))
else
ans.push(nums[t].toString())
t = i
}
return ans
}
The algorithm depends on that the difference between nums[i] and nums[t] is not the same as the difference between i and t. When that happens, the algorithm adds more to the output. This creates a special case when the last range is just a single number, since this cannot trigger the condition.
Hence the hash character is padding to extend the array in order to make the algorithm work, so that the condition nums[i]-nums[t] !== i-t will trigger even for a finishing range of a single number. It could be any string really as long as it is not an integer number.

Backwards JavaScript less-than logic....sometimes

My code couldn't be simpler...
if (iWant > thereAre){
msg = "There's only "+thereAre+" left, but you want "+iWant
} else {
gimmie
}
But sometimes it works.. sometimes it does the else{ every time... sometimes the if{ every time... I will switch the > to a < and then it will still function as before....?
Can JS be broken?
I'm ending up with messages that say "There's only 87 left, but you want 2"... sometimes...sometimes it works great.
The iWant var is getting pulled from a form post
The thereAre var is getting pulled from a MySql COUNT
Please help.. I feel like I'm going crazy.
Sometimes a variable may be a number 4 or the string '4'.
If you want number comparison, not string comparison, then you can multiply by 1 or use parseInt/parseFloat to guarantee that you are dealing with numbers.
if (1*iWant > 1*thereAre ){
too much;
} else {
ok;
}
However, if user input somehow becomes involved and iWant is "two" or "2oops" instead of 2 or "2", this code will still function but not in a useful way.
Optionally you might want to detect non-numbers if it is an issue.

Once value increments digits stops working

I have a function so say i have a list:
1,2,3,4,5,6,7,8,9
and if i click say number 3 , number 3 gets removed and all the values larger than this value will be taken away by one so it'd end up looking like this:
1,2,3,4,5,6,7,8
The only problem is that once we start going into the tenths the function just does not work for example if i had:
8,9,10,11,12,13
its meant to look like if i took 9 like:
8,9,10,11,12
but it goes like this:
8,10,11,12
completely ignorning once we get to double figures.... heres what i have:
$("button").each(function(){
if (pad2(cl_on)<pad2($(this).val())){
$(this).val($(this).val()-1);
}
});
i did have a fix for this going upto 99 but once i go over to 100 onwards the same problem resurects, this is the function i have to fix it upto 99...
function pad2(number) {
return (number < 10 ? "0" : "") + number }
There must be something wrong with even having to use this function... can someone help me so i dont have this problem again say if i reach 1000 or 10000?
Convert the strings to numbers, e.g. using unary +. You can also simplify your code to:
$("button").val(function(i, val) {
return +cl_on < +val ? val - 1 : val;
});
As I said in my comment, you are comparing strings, and in lexical(?) order, 10 comes before 2 for example.
What Felix said, or use parseInt() to achieve the same;
$("button").each(function(){
if (parseInt(cl_on, 10) < parseInt($(this).val(), 10)){
$(this).val(parseInt($(this).val(), 10) - 1);
}

Categories