I want if I clear the text field #t1, text field #d1 should clear. But last two lines dont do it....
function utl()
{
var a = document.getElementById('t1');
var z = document.getElementById('d1');
if (a!=0)
{
var y = parseFloat(a.value) * 100;
y = y || 0;
z.value = y.toFixed(2);
}
else if (a==0)
z.value = 0;
else if (a=='')
z='';
a is a DOM element, and so it will always be != 0 as the != operator will coerce it to a string, and then to a number, and that number will be != 0.
You probably wanted to use the .value property:
var a = document.getElementById('t1').value;
But you'd still have a problem: The value of an input is always a string. In JavaScript, the == and != operators do type coercion, and "" is == 0. So your third statement, z='', will never be reached.
You can use the strict equality operators to figure out what's going on:
var a = document.getElementById('t1').value;
var z = document.getElementById('d1');
if (a === "") { // <== Note! === rather than ==
z.value = "";
} else {
a = +a; // Convert to number intentionally
if (a != 0) {
var y = a * 100;
y = y || 0;
z.value = y.toFixed(2);
} else if (a == 0) {
z.value = "0";
}
}
The strict equality (===) and inequality (!==) operators don't do type coercion, so although "" == 0 is true, "" === 0 is false.
That line where I converted to a number:
a = +a;
...is only one of the many options available. Using +str to convert to a number is the strictest way, but you don't have direct control over the number base. You could also use:
a = parseInt(a, 10); // If you're expecting an integer, or
a = parseFloat(a); // If it may have a fractional portion
...assuming you want base 10 (decimal), but note that they ignore trailing characters, and so parseInt("123laksdjflk", 10) is 123. In contrast, +str (or Number(str)) will say that's Nan because they consider the entire string, not just the first part.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my answer. However, I couldn't pass the test case for "11".
I couldn't find what is wrong in the code. Please help! Thank you!
/**
* #param {number} x
* #return {boolean}
*/
var isPalindrome = function(x) {
if (x === 0) {
return true;
}
if (x < 0 || x % 10 === 0) {
return false;
}
let rev = 0;
while (x > rev) {
pop = x % 10;
x = x / 10;
rev = (rev * 10) + pop;
}
if (x === rev || x === rev / 10) {
return true;
}
else {
return false;
}
};
Finding palindromes is inherently something which you would typically do using strings, not numeric variables, so I suggest converting your number to a string, and going from there:
var isPalindrome = function(x) {
x = x + ""; // convert to string, if x be a number
var isPalindrome = true;
for (i = 0; i < x.length/2; i++) {
if (x.substring(i, i+1) != x.substring(x.length-1-i, x.length-i)) {
isPalindrome = false;
break;
}
}
return isPalindrome;
}
console.log(isPalindrome(1234321));
console.log(isPalindrome(1234329));
The strategy here is just to iterate half the string, and assert that each character matches its counterpart in the other half. Note that we don't need to check the middle character, in the case of an input with an odd number of characters.
Your question seems to be LeetCode 9 and in the discussion board, there are good accepted solutions such as:
JavaScript
var isPalindrome = function(x) {
if (x < 0)
return false;
let reversed = 0;
for (let i = x; i > 0; i = Math.floor(i / 10))
reversed = reversed * 10 + i % 10;
return reversed === x;
};
Python
class Solution:
def isPalindrome(self, x):
if x < 0 or (x > 0 and not x % 10):
return False
return str(x) == str(x)[::-1]
Java
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
int reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return (x == reversed || x == reversed / 10);
}
}
There is another similar isPalindrome question that if you might be interested, I've just copied below:
JavaScript I
var isPalindrome = function(s) {
var original = s.replace(/\W/g, ''); // means NON-WORD characters
var reversed = original.split('').reverse().join('');
return original.toLowerCase() == reversed.toLowerCase();
};
JavaScript II
var isPalindrome = function(s) {
var original = s.replace(/[^a-z0-9]/isg, '');
var reversed = original.split('').reverse().join('');
return original.toLowerCase() == reversed.toLowerCase();
};
Java
class Solution {
public boolean isPalindrome(String s) {
String original = s.replaceAll("(?i)[^a-z0-9]", "").toLowerCase();
String reversed = new StringBuffer(original).reverse().toString();
return original.equals(reversed);
}
}
Python
class Solution:
def isPalindrome(self, s):
s = ''.join(re.findall(r'(?is)[a-z0-9]+', s)).lower()
return s == s[::-1]
\W (non-word-character) matches any single character that doesn't match by \w (same as [^a-zA-Z0-9_]).
Reference
You can find additional explanations in the following links:
LeetCode 9 JavaScript Discussion Board
LeetCode 125 JavaScript Discussion Board
Using string for checking palindrome is very easy and straight forward. Having said that if you want to see how you can do it without changing number to string,
First initialise an variable start with Math.pow(10, digit count-1)
Loop till the value of start is greater than 0
inside loop compare the first and last digit if they are not equal return false
on each iteration remove the first and last digit from x and reduce start by 100
var isPalindrome = function(x) {
// as per question on leetcode negative values cannot be palindrome
if( x < 0) {
return false
}
x = Math.abs(x)
// to get the digits from start we need to get log10 of given value
let len = Math.ceil( Math.max( Math.log10(x), 1 ) ) - 1
let start = Math.pow(10, len)
while(start){
// compare first digit with the last digit
if(Math.floor(x/start) != (x % 10)){
return false
}
// remove first digit of current x
x = x % start
// remove last digit of current x
x = Math.floor(x/10)
// reduce start by 100 as we removed 2 digits
start = Math.floor(start / 100)
}
return true
};
console.log(isPalindrome(1))
console.log(isPalindrome(1221))
console.log(isPalindrome(-121))
console.log(isPalindrome(12341))
console.log(isPalindrome(100111))
Note:- We do (digit count - 1) so that we can capture the first digit
Original leetcode question link
I'm reading a book "Eloquent JavaScript" by Marijn Haverbeke and it says:
"The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ( "" ) count as false, while all the other values count as true."
Would be very nice if someone explains me what did the author mean by saying that NaN counts as false according to the rules of converting?
As I can see it now:
0 == false; // true
"" == false; // true
NaN == false; // false
0 / 0 == false; // false
Yes I know that "NaN is not equal to anything, even to the other NaN", but I just wonder what does the book want me to know?
Basically, if a variable is assigned to NaN, it will evaluate to false if used in a conditional statement. For example:
var b = NaN;
if(b){//code will never enter this block
console.log('the impossible has occurred!')
}
This is true as well if you get invalid input, for example:
var input = "abcd"
var num = parseFloat(input);
if(num){
console.log('the impossible has occurred!')
}
var a = NaN;
var b = null;
var c;
var d = false;
var e = 0;
document.write(a + " " + b + " " + c + " " + d + " "+ e + "<br>");
if(a || b || c || d || e){
document.write("Code won't enter here");
}
if(a || b || c || d || e || true){
document.write("Code finally enters");
}
Reference: link
Other answers are correct, but the significant thing here is that a conversion to a bool takes place in the case that it's used in a condition.
That's why:
NaN === false // false
Yet:
if(NaN) // false because it first does a boolean conversion
// which is the rule you see described
As a side note, NaN == false as used in the question (note == vs ===) actually does a type conversion from false to 0 per the == operator. It's beyond the scope of this question, but the difference in operators is well documented elsewhere.
The book wants you to know that JavaScript evaluates NaN to false.
var notANumber = 500 / 0;
if(notANumber) {
// this code block does not run
}
else {
// this code block runs
}
How would i check if a decimal is negative? Because the if statement automatically turns it into a number...
Example:
var x = -0.24324;
how would i parse it so it tells me x is negative/positive?
Thanks
Edit: Maybe i phrased it badly, the variable changes so something it will be positive like 0.00000001, sometimes -0.0003423423, sometimes 0.0000000234
If i put it in a if statement everything is automatically turned into 0 right? And i can't use a parseFloat in the if statement?
Just check if x less than zero since it's a number:
if (x < 0) {
// it's negative
}
You can use isNaN() function to check whether it is valid number or not.
If it is, then you can check for positive or negative value.
Something like this:
var x = "-123"
var y = -456;
var z = '-123a';
if(!isNaN(x) && x < 0) {
console.log(x + ' is negative');
}
if(!isNaN(y) && y < 0) {
console.log(y + ' is negative');
}
if(!isNaN(z) && z < 0) {
console.log(z + ' is negative');
}
const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
// ✅ ES6 Way
Math.sign(num); // -1
I have to write Java script that can read two integers from the user, if the first number the user entered is evenly divisible by the second number, then it will display an alert of TRUE to the user, and FALSE otherwise. If either number the user enters is ZERO the alert should display FALSE to the user.
this is my code it does not work
var y = prompt("Enter a Value","");
var z = prompt("Enter a Value","");
if (y % z === 0) {
greeting = "TRUE";
} else (y % z !== 0 ||
{
greeting = "FALSE"
document. get Element By Id ("true false").inner HTML = greeting;
If either number the user enters is ZERO the alert should display
FALSE to the user.
change you if condition to
if (x && y && y % z === 0) {
Rest of the code is
if (x && y && y % z === 0)
{
greeting = "TRUE";
}
else
{
greeting = "FALSE";
}
If you are new to javascript here is another way to implement this very common pattern using the ternary operator:
var greeting = (x && y && y % z === 0) ? "TRUE" : "FALSE";
Consider the code snippet below from this AngularJS tutorial:
app.factory('Auth',
function ($firebaseSimpleLogin, FIREBASE_URL, $rootScope) {
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
register: function (user) {
return auth.$createUser(user.email, user.password);
},
signedIn: function () {
return auth.user !== null;
},
logout: function () {
auth.$logout();
}
};
$rootScope.signedIn = function () {
return Auth.signedIn();
};
return Auth;
});
I understand the difference between != and !== is the first compares by reference and the second compares by value. Since the comparison here is to null, then why has the developer chosen to use !== instead of !=? Is my understanding correct that both would work here?
== / != operator only compares the value of the variables, not the type
=== / !== operator compares the type and the value of the variables
Some examples:
var varA = 5; // int
var varB = '5'; // string
var varC = 5; // int
if(varA == varB) // true (only value compared)
if(varA === varB) // false: because varB is of type string and varA of type int
if(varA == varC) // true
if(varA === varC) // true: because varA and varC are of the same type and have the same value
I often use "if(x != null)" to check if x is either null or undefined. It's safer than just saying "if(x)" since there are other falsey values besides null and undefined.
Here's an overview table, for your convenience: http://jsfiddle.net/QQcVw/1/
0 "" false null undefined
0 Y Y Y n n
"" Y Y Y n n
false Y Y Y n n
null n n n Y Y
undefined n n n Y Y
As you can see, == considers equal three empty "values" (0, "" and false) and two "non-values" (null and undefined). See javascript standard for the exact algorithm.
In most cases, it's a good idea to avoid == and always stick to ===.