NaN , Returning in browser - javascript

I get back
Nan ,
what does this mean?
In the distinctPlayer variable are two values 110 and 115. I want to have for this two Player the name and the sum of Note.
The first query of finalTotal gives for 110 the sum of Note 8 + 2 = 10 and for 115 the sum of Note 4 + 3 = 7 back.
The second query ... name of 110 is Dave and for 115 is Tom.
The while loop have an execution of 2 times. Then I try to safe each line of while in a variable. First line is Dave: 10 and second line is Tom: 7. But I don't get this back. At the moment the result is NaN ,
In the html the function is defined as
<p>
<pre>{{otherHelperFunction}}</pre>
</p>
And here is the function
var d = 0;
while(distinctPlayer[d]) {
var finalTotal = Spieltag.find({SpielerID: distinctPlayer[d]}).map(function (doc) {
total =+ doc.Note;
});
var finalName = Spieltag.find({SpielerID: distinctPlayer[d]}).map(function (doc) {
return doc.Name;
});
var finalReturn =+ finalName +" "+ finalTotal;
d++;
}
return finalReturn;

NaN means Not a Number. Try the following:
var finalReturn = finalName + " " + finalTotal;
The addition assignment operator is += which can be used as follows:
var a = 1;
a += 1 // a now has a value of 2
The += operator in this case represents a = a + 1.

You're using =+, the correct syntax is +=

Let's go,
NaN is Not a Number, you are trying treat as number what not Number.
You are using =+, you should use +=.
Probabily the doc.Note not is number.
JavaScript have function isNaN, this return a boolean.

Related

Need help on Highest and Lowest (codewars)

Hello I'm stuck on an edge case in a coding challenge: would be great if someone could help;
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
Notes:
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.
Here is my code in Javascript:
function highAndLow(numbers){
numbers2=numbers.split(' ');
var highest =parseInt(numbers2[0]);
var lowest =parseInt(numbers2[0]);
if (numbers2.length==1) {
return numbers;
}
else {
for (i=0;i<numbers2.length;i++) {
if (parseInt(numbers2[i])>highest) {
highest = parseInt(numbers2[i]);
}
else if (parseInt(numbers2[i])<lowest) {
lowest = parseInt(numbers2[i]);
}
}
}
return(highest + " " + lowest);
}
I can pass 17 tests but am stuck on an Expected '42 42' because I am returning '42' which is puzzling to me. Any help appreciated :]
I think you should just add <= and >= instead of > and <so the both conditions are satisfied
You can also do it by sorting the array and then choosing the first and last element from the sorted array.
function highestAndLowest(nums) {
let numbers = nums.split(' ');
let sorted = numbers.sort(function (a, b) {
return Number(a) - Number(b);
});
return sorted[0] + " " + sorted[sorted.length - 1];
}
https://jsbin.com/farapep/edit?js,console
This can be faster depending on the browsers sort implementation, the size of the array, and the initial order of the array.
I think it will work well just like this
function highAndLow(numbers){
numbers = numbers.split(" ");
return Math.max(...numbers) +" "+ Math.min(...numbers);
}
if (numbers2.length==1) {
return numbers;
}
That means if just "42" passed, you return "42". Thats not required here. Just remove that and it should work. How i would write it:
function getMaxMin(numbers){
numbers = numbers.split(" ");
return Math.max(...numbers) +" "+ Math.min(...numbers);
}
or your code a bit beautified:
function getMaxMin(numbers){
var max,min;
numbers = numbers.split(" ");
for( var num of numbers ){
if( !max || num > max ) max = num;
if( !min || num < min ) min = num;
}
return max+" "+min;
}
Kotlin
fun highAndLow(numbers: String): String {
val s = numbers.split(" ").sorted()
return "${s.last()} ${s.first()}"
}
or in one line
fun highAndLow(numbers: String): String = numbers.split(" ").sorted().run { "${first()} ${last()}" }
Let us consider the given example:
highAndLow("1 2 3 4 5"); // return "5 1"
On calling function highAndLow with arguments ("1 2 3 4 5"), output should be "5 1".
So my function takes the argument. Each number is picked upon on the basis of space between them(used split method). I have used ParseInt to specify the datatype, because var can be anything(string/integer). The algorithm used is very basic one which considers the first number as the maximum and compares its with the rest of the arguments. Value of max is updated if it finds a number greater than itself. Same algorithm is used for min value also. The return statement is designed to get the value in specific way as mentioned in the example.
function highAndLow(numbers){
num=numbers.split(' ');
var max = parseInt(num[0]);
var min = parseInt(num[0]);
for (var i = 0; i <= num.length; i++) {
if(parseInt(num[i]) > max){
max = parseInt(num[i]);
}
}
for (var i = 0; i <= num.length; i++) {
if(parseInt(num[i]) < min){
min = parseInt(num[i]);
}
}
return (max + " " + min);
}
You can also use inbuilt methods min and max. I wanted to solve this question without using them.

Function that returns a multiplication table fails with negative numbers

Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns
10.2 = 20
10.3 = 30
10.4 = 40
This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate
10.-4 = -40
10.-3 = -30
10.-2 = -20
10.-1 = -10
but it doesn't return anything. This is my code:
function tabmul(a,b,c){ \\function that generates the multiplication table
var myarray = new Array();
var x
for(x=b; x<=c; x++){
myarray[x - b] = a*x;
document.write(a + "." + x + "=" + myarray[x - b] + "<br>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
tabmul(a,b,c);
} else {
alert("The starting point is bigger than the ending point");
}
You are comparing strings. This is because prompt returns strings. you need to convert a,b,c to numbers. Also you are using wrong symbols for comments, you need to correct those.
function tabmul(a,b,c){ //function that generates the multiplication table
a = Number(a);
b = Number(b);
c = Number(c);
var myarray = new Array();
var x
for(x=b;x<=c;x++){
myarray[x-b] = a*x;
document.write(a+"."+x+"="+myarray[x-b]+"<br/>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
if(0 <= c-b){ //this checks if the starting point is smaller or equal than the ending point of the table
tabmul(a,b,c);
}
else{
alert("The starting point is bigger than the ending point");
}
1)Make normal names for function arguments.
2)Use indentation and 'let' in 'for' loop instead of 'var' right before:
for(let x = b; x <= c; x++){}
3)Don't forget semicolons.
function multiplication(val, start, end) {
if(end - start <= 0) return;
for(let i = start; i <= end; i++) {
console.log(val + ' * ' + i + ' = ' + val * i);
}
}
multiplication(10, -4, -1);
10 * -4 = -40
10 * -3 = -30
10 * -2 = -20
10 * -1 = -10
You should also convert your input to a number using Number or parseInt to make sure it is numeric.
After that you can run into problems referring to an array by index using a negative number.
myarray[x-b] // can fail if x-b<0. Also for a large number n it will insert empty elements in your array up to N.
For example take the following:
var myarray= new Array();
myarray[-4]=1;
console.log(JSON.stringify(myarray));
// result "[]"
myarray= new Array();
myarray[10]=1;
console.log(JSON.stringify(myarray));
// result "[null,null,null,null,null,null,null,null,null,null,1]"
You could convert it to a string:
myarray['"' + (x-b) + '"'] = a*x;
Or you could just use push() and your indexes will start with zero.:
for(x=b;x<=c;x++){
myarray.push(a*x);
document.write(a+"."+x+"="+myarray(myarray.length-1)+"<br/>")
}

Calculate in Javascript not working

I want to calculate in Javascript but having Strange Problems.
It just adds an 1 to my String but it should calculate it. I am converting my Strings to Int with the parseInt() Function and a am calculating like this: sec = sec + 1;
var calc= parseInt($(this).find("input[name=calc]").val());
calc = calc + 1;
Your string must not be empty if don't want NaN. First check if you get an empty string:
var cal = null;
if ( $(this).find("input[name=calc]").val() ) {
cal = parseInt( $(this).find("input[name=calc]").val(), 10 );
cal++;
}
if(!!sec){
sec = parseInt(sec, 10) + 1;
alert(sec);
}
Or, in your scenario:
var fieldvalue = $(this).find("input[name=calc]").val(), calc;
if(!!fieldvalue){
calc = parseInt(fieldvalue, 10);
calc += 1;
alert(calc);
}
Do you have more code to express. It may just be coming out to 1, because sec is not set as a number
In javascript, the + operator is used for addition and concatenation of strings.
As javascript is weakly typed, you have to add information about the type. Here are two solutions:
Substract 0 from the string
sec = (sec-0) + 1;
Add unary + operator to the string
sec = (+sec) + 1;

Why I got NaN in this javaScript code?

First I test that every variable got a number value:
09-11 18:15:00.420:
d_drop: -1.178791867393647
drop_at_zero: 0.0731037475605623
sightHeight: 4.5
d_distance: 40
zeroRange: 10
09-11 18:15:00.420:
d_drop: true
drop_at_zero: true
sightHeight: true
d_distance: true
zeroRange: true
function isNumber (o) {
return ! isNaN (o-0) && o != null;
}
var d_drop; // in calculation this gets value 1.1789
var d_path = -d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm");
and in the log:
09-11 18:15:00.430: D/CordovaLog(1533): Path: NaN cm
WHY? I have tried to figure that out couple of hours now and no success, maybe someone has an idea, I haven't!
Thanks!
Sami
-------ANSWER IS that parse every variable when using + operand-----------
var d_path = parseFloat(-d_drop) - parseFloat(sightHeight) + (parseFloat(drop_at_zero) + parseFloat(sightHeight)) * parseFloat(d_distance) / parseFloat(zeroRange);
The addition operator + will cast things as strings if either operand is a string. You need to parse ALL of your inputs (d_drop, sightHeight, etc) as numbers before working with them.
Here's a demo of how the + overload works. Notice how the subtraction operator - is not overloaded and will always cast the operands to numbers:
var numberA = 1;
var numberB = 2;
var stringA = '3';
var stringB = '4';
numberA + numberB // 3 (number)
numberA - numberB // -1 (number)
stringA + stringB // "34" (string)
stringA - stringB // -1 (number)
numberA + stringB // "14" (string)
numberA - stringB // -3 (number)
http://jsfiddle.net/jbabey/abwhd/
At least one of your numbers is a string. sightHeight is the most likely culprit, as it would concatenate with drop_at_zero to produce a "number" with two decimal points - such a "number" is not a number, hence NaN.
Solution: use parseFloat(varname) to convert to numbers.
If you're using -d_drop as a variable name, that is probably the culprit. Variables must start with a letter.
var d_drop = -1.178791867393647,
drop_at_zero = 0.0731037475605623,
sightHeight = 4.5,
d_distance = 40,
zeroRange = 10;
var d_path = d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm"); // outputs: Path: 12.613623122848603 cm

get the number of n digit in a 2+ digit number

For example, getting "5" in "256". The closest I've gotten is Math.floor(256/10)), but that'll still return the numbers in front. Is there any simple way to get what I want or would I have to make a big function for it? Also, for clarity: "n digit" would be defined. Example, getDigit(2,256) would return 5 (second digit)
Math.floor((256 / 10) % 10)
or more generally:
Math.floor(N / (Math.pow(10, n)) % 10)
where N is the number to be extracted, and n is the position of the digit. Note that this counts from 0 starting from the right (i.e., the least significant digit = 0), and doesn't account for invalid values of n.
how about
(12345 + "")[3]
or
(12345 + "").charAt(3)
to count from the other end
[length of string - digit you want] so if you want the 2 it's:
5 - 4 = 1
(12345 + "")[1] = "2"
function getNumber (var num, var pos){
var sNum = num + "";
if(pos > sNum.length || pos <= 0){return "";}
return sNum[sNum.length - pos];
}
First, you need to cast the number to a string, then you can access the character as normal:
var num = 256;
var char = num.toString()[1]; // get the 2nd (0-based index) character from the stringified version of num
Edit: Note also that, if you want to access it without setting the number as a variable first, you need a double dot .. to access the function:
var char = 256..toString()[1];
The first dot tells the interpreter "this is a number"; the second accesses the function.
Convert to string and substring(2,2)?
This should do it:
function getDigit ( position, number ) {
number = number + ""; // convert number to string
return number.substr ( position + 1, 1 ); // I'm adding 1 to position, since 0 is the position of the first character and so on
}
Try this, last line is key:
var number = 12345;
var n = 2;
var nDigit = parseInt((number + '').substr(1,1));
If you want to try to do everything mathematically:
var number = 256;
var digitNum = 2;
var digit = ((int)(number/(Math.pow(10,digitNum-1))%10;
This code counts the digit from the right starting with 1, not 0. If you wish to change it to start at 0, delete the -1 portion in the call.
If you wish to count from the left, it gets more complicated and similar to other solutions:
var number = 256;
var digitNum = 2;
var digit = ((int)(number/(Math.pow(10,number.tostring().length-digitNum))%10;
edit:
Also, this assumes you want base 10 for your number system, but both of those will work with other bases. All you need to do is change instances of 10 in the final line of code to the number representing the base for the number system you'd like to use. (ie. hexadecimal =16, binary = 2)
// You do not say if you allow decimal fractions or negative numbers-
// the strings of those need adjusting.
Number.prototype.nthDigit= function(n){
var s= String(this).replace(/\D+/g,'');
if(s.length<=n) return null;
return Number(s.charAt(n))
}
use variable "count" to control loop
var count = 1; //starting 1
for(i=0; i<100; i++){
console.log(count);
if(i%10 == 0) count++;
}
output will fill
1
2
3
4
5
6
7
8
9

Categories

Resources