Here is a boolean-logic - javascript

Write a JavaScript function named findTen that reads two numbers from two text fields and then outputs to a div "True" if either one of them is 10 or both of them are 10 or if their sum is 10. Otherwise your function should output "False" to the div.
This is what I have so far, but it is not outputting correctly. Something is wrong with my else if statement:
<script>
function findTen() {
var a = document.getElementById("one").value;
var b = document.getElementById("two").value;
var doTheMath = a + b;
if ( a == 10 || b == 10) {
alert("true");
}
else if (doTheMath == 10 ) {
alert("true");
}
else {
alert(a b doTheMath);
}
document.getElementById("output").innerHTML = c;
}
</script>

There are a few errors in your posted code:
a and b are strings, so doTheMath is actually a string. In the case of a = 5 and b = 5, doTheMath is '55'. They need to be converted, in one of a number of ways. I chose Number:
var doTheMath = Number(a) + Number(b);
alert(a b doTheMath) is improper syntax. You should look to concat them:
alert(a + ' ' + b + ' ' + doTheMath);
c is undefined in your assignment at the end. So in your if/else blocks you probably want a statement like: c = false;
You can see all these problems fixed in this jsfiddle.

Your problem is that it handles the inputs as Strings and not as integers.
what you have to do is make the strings into integers by using the parseInt function

Your a and b variables are strings because you just got them out of text fields. In JavaScript, if you use the + operator on strings it will concatenate them. This is rather unfortunate 'feature' of javascript. To add the values from text fields you first need to convert them to integers:
var doTheMath = parseInt(a) + parseInt(b);
Furthermore, I don't think this statement will work at all:
alert(a b doTheMath);
Alert takes a string, so if you want to display those three values you'll need to concatenate them e.g.
alert(a + ' + ' + b + ' = ' + doTheMath);

Related

Javascript - Don't understand data type of a variable

I have the following:
this.replaceBand1 = "1";
...
var replaceEndValue = Integer.valueOf(this.replaceBand1);
replaceBeginValue = replaceEndValue + 1;
//what is going on?
var type1 = typeOf replaceEndValue;
var type2 = typeOf replaceBeginValue;
log.debug("replaceEndValue: " + replaceEndValue + " " + type1);
log.debug("replaceBeginValue: " + replaceBeginValue + " " + type2);
...
setValue(column1, replaceEndValue);
setValue(column2, replaceBeginValue);
My expected outcome: replaceBeginValue will equal 2, and I can pass that into the function setValue that requires an Integer.
Actual outcome: replaceEndValue works, replaceBeginValue does not work.
The first debug shows - replaceEndValue: 1 object
The second debug shows - replaceBeginValue 2 string
I have no idea why replaceBeginValue is a string. Can anybody help?
You would need parseInt instead of Integer.valueOf. The function parseInt returns an int primitive type.
If you would like replaceBeginValue to equal 2, you would need something like this:
this.replaceBand1 = "1";
...
var replaceEndValue = parseInt(this.replaceBand1);
replaceBeginValue = replaceEndValue + 1;
...
Note: Integer.valueOf is for Java not JavaScript.

Displaying current & total page number N(N)

I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;
You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.
Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}

JS - summing elements of arrays

I'm trying to make operations with numbers that are stored in arrays, unfortunately they seem to be considered as "text" rather than numbers, so when I do like array1[i] + array2[i], instead of doing 2+3=5 I would get 2+3=23 ...
The values of these arrays come from fields (html)
No idea how to deal with that ;D
Thanks for your help
If you wanna look at my code, here's what it looks like :
var polynome = [];
for (var i=0; i<=degree; ++i) {
polynome[i] = document.getElementById(i).value;
}
var a = document.getElementById("a").value;
var tempArray = [];
var quotient = [];
quotient[degree+1] = 0;
for (var i=degree; i>=0; --i) {
tempArray[i] = a * quotient[i+1];
quotient[i] = polynome[i] + tempArray[i];
}
document.getElementById("result").innerHTML = polynome + "<br>" + tempArray + "<br>" + quotient;
array1[i] contains string and not int so when you are trying both elements with + operator it is concatenating both the values rather of adding them
you need to cast both elements in arrays to integer
try this
parseInt( array1[i] ) + parseInt( array2[i] )
The + punctuator is overloaded an can mean addition, concatenation and conversion to number. To ensure it's interpreted as addition, the operands must be numbers. There are a number of methods to convert strings to numbers, so given:
var a = '2';
var b = '3';
the unary + operator will convert integers and floats, but it's a bit obscure:
+a + +b
parseInt will convert to integers:
parseInt(a, 10) + parseInt(b, 10);
parseFloat will convert integers and floats:
parseFloat(a) + parseFloat(b);
The Number constructor called as a function will convert integers and floats and is semantic:
Number(a) + Number(b);
Finally there is the unary - operator, but it's rarely used since subtraction (like multiplication and division) converts the operands to numbers anyway and it reverses the sign, so to add do:
a - -b

I need a explaining for this short script

I have this code :
function list(target, letters, lvls) {
var index = 0;
(function iter(s, lvl) {
if(lvl++ == lvls)
return target.appendChild(document.createTextNode(
++index + ' - ' + s + '\n'
));
for(var i=0; i<letters.length; ++i)
iter(s + letters[i], lvl);
})('', 0);
}
list(document.getElementById('output'), 'abc', 3);
But I don't know this type of function syntax.
Can some one explain to me the function behavior and what this code exactly do step by step.
And thanks in advance
This seems to be iterating through the string 'abc' and creating as many X letter strings as possible with the combination of all the characters in the string.
So the call is list([element ID to output strings], [string of all possible letters], [size of strings to generate])
So the following example -
<script type="text/javascript">
function list(target, letters, lvls) {
var index = 0;
(function iter(s, lvl) {
if(lvl++ == lvls)
return target.appendChild(document.createTextNode(
++index + ' - ' + s + '\n'
));
for(var i=0; i<letters.length; ++i)
iter(s + letters[i], lvl);
})('', 0);
}
list(document.getElementById('output'), 'ab', 2);
</script>
<div id="output"></div>
will output all possible two letter strings (defined by param 3), using the characters from the input string (param 2) and will result in -
1 - aa 2 - ab 3 - ba 4 - bb
Explanation
Inside the method there is a second called iter with the arguments s and lvls. On
first run, the arguments parsed to the iter method are blank and 0. It hits the for
loop which runs until all of the letters in the string letters have been used up,
each time recursively calling the iter method. Each time it adds the current letter in
the iteration s, along with the next letter in the string letters[i]. Every time it
recursively calls itself it builds up the string until the number of specified levels have
been reached for that particular string and then returns the result, along with the index
value. This is just a numeric value to represent the string count.

How to ignore "-" and "." characters in a value during sort comparison?

I have an html page that has a field that can be sorted. I also have created a javascript function that can sort that field in order. Let's imagine p_cSort is the 'id' name of that field.
function change_sort(neworder) {
document.sortForm.p_cSort.value = neworder;
document.sortForm.submit();
However when I have values like
12.34
12-35
12.36
12-33
and I search for them on my search page. The results returned are
12.34
12.36
12-33
12-35
How can I ignore the characters "." and "-" when sorting?
So the result I am looking for should be:
12-33
12.34
12-35
12.36
Why don't you make a custom sort function liek this:
var x = ['12.5', '11.3', '13-5', '10-0'];
x.sort(function(a, b){
a = a.replace(/[-]/, '.');
b = b.replace(/[-]/, '.');
if( parseInt(a) < parseInt(b) ) return -1;
if( parseInt(a) > parseInt(b) ) return 1;
return 0;
});
Output:
["10-0", "11.3", "12.5", "13-5"]
This will also work if you have 125.5 and so on. because the . and the - are both used in the compare.
Example with >= 100
So input:
["100-0", "11.3", "12.5", "13-5"]
Will output
["11.3", "12.5", "13-5", "100-0"]
Short answer is using replace and sort function:
"12.34".replace(/[.-]/, '')
Full answer
var a = ["12.34", "12-35", "12.36", "12-33"];
var b = a.sort(function(a, b){
return parseInt(a.replace(/[.-]/, '')) - parseInt(b.replace(/[.-]/, ''))
});
// now b contain sorted array
// ["12-33", "12.34", "12-35", "12.36"]

Categories

Resources