Getting a NaN on a variable that is quite clearly a number - javascript

This is by far the strangest error I've ever seen.
In my program I have one variable called avgVolMix. It's a decimal variable, and is not NaN (console.log(avgVolMix) prints something like 0.3526246 to console). However, using the variable at all in an assignment statement causes it to corrupt whatever is trying to use it to NaN. Example:
console.log(avgVolMix); <- prints a working decimal
var moveRatio = 10 + avgVolMix * 10;
console.log(moveRatio); <- prints NaN
I seriously have no idea why this is happening. I've tried everything to fix it; I've converted it to a string and then back, rounded it to 2 decimal places, adding 0.0001 to it - nothing works! This is the only way I can get it "working" right now:
var temp = 0.0;
for(i = 0; i <= avgVolMix; i+=0.1)
temp = i;
This assigns a number that is close to avgVolMix to temp. However, as you can see, it's extremely bad programming. I should also note that this isn't just broken with this one variable, every variable that's associated with a library I'm using does this (I'm working on a music visualizer). Does anyone know why this might be happening?
Edit: I'm not actually able to access the code right now to test any of this stuff, and since this is a company project I'm not comfortable opening up a jsfiddle anyway. I was just wondering if anyone's ever experienced something like this. I can tell you that I got the library in question from here: http://gskinner.com/blog/archives/2011/03/music-visualizer-in-html5-js-with-source-code.html

If its showing the variable value as NaN. Then try converting the variable as parseInt(); method. Hope it works. Because I also faced such problem and solved when tried it.

Related

using .substring after .replace is creating an error sometimes, how could I properly structure the substring so that it always works?

I'm getting an error with my code below. I am trying to make a calculator, and I am using strings as input and typecasting in order to solve. The calculator was working fine, but now I am trying to add an ans button to allow for having equations based on previous answer. I am having an issue with the substrings now, and in equations where ans comes first like 'ans+88" I get NaN as a result and 88 turns into undefined. But when I switch the substring parameters it messes it up for other types of equations as described in the comments below.
link to repository
else if(equation.indexOf("+") != -1){
//this finds the the index of +
let pInd = equation.indexOf("+")
/*before I added this, it worked properly, firstValue would get the firstvalue
secondvalue would get the second value and it added correctly
the point of the if statement is to replace ans with props.prevResult which is
the previous answer from the previous entered equation. After it replaces it
removes the whitespace*/
if(equation.includes("ᴀɴs")){
equation = equation.replace(/ᴀɴs/gi, String(props.prevResult))
//my attempt to remove whitespace since i thought it might be the issue
// but now I'm pretty sure the issue is with substring.
equation = equation.replace(/\s/g, '')
}
equation = String(equation)
firstVal = equation.substring(0,pInd)
//this line is where the error seems to come from
secondVal = equation.substring(pInd+1,equation.length)
/* when ans is first such as in 'ans + 9" 9 becomes undefined ans stays
correct. I tried replacing it with pInd+1, equation.length-1, but that
made it so that equations like '9+ans' were cut short,
and regular ('1+55') equations also broke.*/
result = parseFloat(firstVal)+parseFloat(secondVal)
props.setInput(result)
props.setPrevResult(result)
setResultGot(true)
}
The solution #james gave solved the issue, the position of the + sign was obviously going to change after I replaced ans, so that line just had to be moved to after the replacement, silly mistake, I appreciate the help.

Does this kind of value setting work in Javascript?

I'm trying to create code that requires the least number of bytes and that works for all browsers including IE 7.
In this example, the program calls dosomething('x1') and dosomething('x2').
If I have code like this:
var items,item,index,count;
items=Array('x1','x2');
count=items.length;
for (index=0;index<count;index++){
item=items[index];
dosomething(item);
}
Could I reduce it to this and have it still function exactly the same in all browsers:
var a=Array('x1','x2'),c=a.length,i;
for (i=0;i<c;i++){
f(a[i]);
}
I understand I changed the variable names and calling function name but my goal is to use the least number of bytes possible in the code to make the code execute.
I'm just not sure if declaring a variable equal to a property of a value from a previous variable in the same list of declarations would actually return correct results.
In other words, does var a=Array('x1','x2'),c=a.length... work, or do I have to specifically do var a=Array('x1','x2');var c=a.length; to make it work in all browsers including IE 7?
This is what the Google Closure Compiler service returned:
var a,b,c,d;a=["x1","x2"];d=a.length;for(c=0​;c<d;c++)b=a[c],dosomething(b);
You can find many different Javascript compressors online to automate the process you are hand coding now. Yet, it's always good to understand how they work as it helps to write code that is better compressed.
As for IE, you can test your code by changing the emulations settings in the IE debugger panel. Just press F12, click the Emulation tab, and adjust the document mode to 7 (IE7).
Hope this is enough to get you started in the right direction.
You can use Array.map from IE 9
var items = Array('x1','x2');
items.map(dosomething(item));

javascript losing decimals during assignment

I am trying to do a simple thing but for some reason it is not working. I am using Knockout and I have a model which I update after user enter some data and use the same to communicate back to C# code on server side. For some reason, when I try to assign decimal value to one of the member of model it isn't working. Though, in this case I am using knockout, I believe it has nothing to do with KO. See the screenshot where I have the value 22.78 and I am trying to do parseFloat but it ends up as just 22. I tried other things such as removing he parseFloat just to see if it accepts the string value as it is but even that is not working. Can someone help?
Your doing Bitwise OR while assigning the value.
this.AMOUNT_RECEIVED = parseFloat(data.AMOUNT_RECEIVED) | 0;
so only it returns 22. Because 22.78 | 0 is 22.
Please check this code.
console.log(22.78 | 0);
Please try this code while assigning value. You can get decimal values without loss.
this.AMOUNT_RECEIVED = parseFloat(data.AMOUNT_RECEIVED);
Pelase Check below link for more details.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR
try this (please notice the double || )
this.AMOUNT_RECEIVED = parseFloat(data.AMOUNT_RECEIVED) || 0;

Javascript decrements integer when it is appended to a string

I have the weirdest thing happening to some integers in my front-end.
Javascript, true to its legacy, decides to decrement integers if I decide to add them to a string. Not all, mind you, but only some, because if it was all that would be too simple.
Here is an example.
var jid = 10152687447723705;
$('#slide_2_inner').html("<img src='//graph.facebook.com/"+jid+"/picture?width=80&height=80' width='80' height='80' />");
This code fetches the Facebook profile picture of user with ID 10152687447723705 (a friend of mine) and displays it inside the slide_2_inner div. Or at least it's supposed to, because when the HTML shows up, the image location is wrong. Why is it wrong? Because instead of //graph.facebook.com/10152687447723705/picture?width=80&height=80 it's //graph.facebook.com/10152687447723704/picture?width=80&height=80.
So, you see, 10152687447723705 got turned into 10152687447723704, somehow.
When I do this instead...
var jid = "10152687447723705";
$('#slide_2_inner').html("<img src='//graph.facebook.com/"+jid+"/picture?width=80&height=80' width='80' height='80' />");
...the URL is created correctly and the image shows up.
But wait, it gets worse. Let's try the first way again, but with a different Facebook ID:
var jid = 1593894704165626;
$('#slide_2_inner').html("<img src='//graph.facebook.com/"+jid+"/picture?width=80&height=80' width='80' height='80' />");
Guess what? It works! The image shows up.
So, the question is, why is this craziness happening and how do I stop it from happening?
Could it have to do with the fact that one number is odd and the other is even? I don't have enough data to confirm the pattern.
In the example that doesn't work, doing jid = jid.toString() doesn't change anything.
The main thing for me is understanding the root cause. I'm sure I could find some hacky solution, put the integer through some function to turn it into something that will work, but I'd prefer to get to the bottom of this properly.
The maximum integer value that is safe to use in JS is 2^53 - 1 (Number.MAX_SAFE_INTEGER). Integer values higher than that are prone to precision errors.
Facebook IDs are usually larger than that, thus they have to be represented by a string. That should not be a problem since one does not use IDs for mathematically computations anyway.

Subtracting large integers

So. I'm trying to subtract large integers. 76561198060995608 - 76561197960265728 = 100729880 type numbers. (I'm converting a 64 bit to a 32 bit) Vbscript and JS both give 100729888.
I would love to be able to do it in vbscript, but I'm either doing something wrong with cdbl (returns 100729888) or ccur (Overflow: 'ccur' error happens) or it can't be done the way I'm trying.
I've tried implementing JS libraries (bignum, bignumber) and they also haven't returned the correct number, again, maybe because of my error. BigNumber returns 100729890.
Big number code as follows:
$(document).ready(function(){
var x = new BigNumber(76561198060995608).subtract(new BigNumber(76561197960265728))
alert(x)
})
So...what am I doing wrong? Am I making a stupid mistake? I don't feel like this should take the 6+ hours it's taken me so far.
Any suggestions or help would be greatly appreciated. Thanks!
The problem is that when you try
new BigNumber(76561198060995608)
you're still relying on the JavaScript runtime to parse and represent that number before it calls the "BigNumber" constructor. I'm pretty sure you can pass a string to that constructor:
new BigNumber("76561198060995608")
and that should give you a fighting chance.

Categories