I am working on a BIRT Report and one of the fields contains the following expression:
dataSetRow["user_id"] != dataSetRow["creatorId"] ? dataSetRow["orderCreator"] : ''
What is the logic of this statement?
That statement is the equivalent of the code below, and is called the 'ternary' operator:
var value;
if(dataSetRow["creatorId"]){
value = dataSetRow["orderCreator"];
}
else{
value = '';
}
//To be clear, this isn't assigning to anything - this is the same expression you have in your question.
dataSetRow["user_id"] != value
You could use that expression, which returns a boolean, in an if block, for example:
if(dataSetRow["user_id"] != value){
//Do something
}
Related
I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.
my code:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
above program should return not accepted
value of myCondition attribute can be very complex for example:-
'hello' == 'hello'
5>1 etc
I guess what you need is the eval function. As it says in the provided link:
The eval() function evaluates JavaScript code represented as a string.
So, you can change your code like this:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
P.S: That being said, I don't think doing it like this really safe.
I have the following JavaScript logical condition using the ternary operator:
var columnheader = (elem.getText === "ID") ? (Page.TableColumn(elem.getText())) : (Page.TableColumn(toTitleCase(elem.getText())));
For some reason when elem.getText value is 'ID' with no whitespace it doesn't evalute the first expression only the second, is there something wrong in my syntax? I've checked and double checked!
getText is a function. In your code, you are comparing the function with "ID", not the result of the function call (getText() ).
Should be:
var columnheader = (elem.getText() ==="ID") ? (Page.TableColumn(elem.getText())) : (Page.TableColumn(toTitleCase(elem.getText())));
I have a jquery function which receives a parameter from it callers. Calling split() on the parameter throws error. Here is the function
function formatNairaCurrency(value) {
var formatedWithoutNaira;
var formattedAmount
//check if value is in kobo format
var splittedValue = value.split(".");//Throws error
if (splittedValue.length === 2) {
formatedWithoutNaira = isNaN(splittedValue[0]) ? "" : splittedValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + splittedValue[1];
} else {
formatedWithoutNaira = isNaN(value) ? "" : value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + ".00";
}
return formattedAmount;}
The call var splittedValue = value.split("."); throws the error value.split is not a function
What am I missing?
I am calling this in a .cshtml file. This works in another function even on the same .js file. The difference is that the value was not a parameter but a value from a text box.
Your help is greatly appreciated.
If i understand your intention correctly you are trying to use split for string. Your error could be caused by the fact that value is not string. You need to debug or throw to console 'value'.
Edit: For example if
value is null, or value is undefinded this would most definitely cause your error. Testing for those conditions:
(value === null)
(typeof value === 'undefined')
If your value is number - that would cause error too. You need to cast number to string first. You can do it by
var valueAsString = value.toString();
valueAsString.split('.');
I am writing a program to identify special numbers according to the criteria laid out in this code wars kata:
http://www.codewars.com/kata/catching-car-mileage-numbers
Here is a link to my full code and tests:
http://www.codeshare.io/UeXhW
I have unit tested my functions which test for each of the special number conditions and they appear to be working as expected. However, I have a function:
function allTests(number, awesomePhrases){
var num = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros(num) || sameDigits(num) || incrementing(num) || decrementing(num) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
which determines if any of the criteria of being a special number is met and that's not working as expected. For example, when I tested the allZeros() function on 7000 it returned true, but alltests(7000) is returning false. Is there something about how chains of logical expressions are evaluated that I don't understand or is the problem something else?
I have looked at W3schools and MDN to try and diagnose the problem.
Change all your !== to != will do.
False results as long as allTests() executes with a second argument even it it's the empty string, as follows:
allTests(7000,"");
If the function is called with just one argument, i.e. the number, expect this error:
Uncaught TypeError: Cannot read property 'length' of undefined
The error message refers to one of the functions in the logic chain, namely matchPhrase() which expects two parameters: number and awesomePhrases. If instead of providing an empty string, you use null, you'll also get the same error message.
JavaScript doesn't support the concept of default parameters -- at least not in a way that one might expect; the parameters default to undefined. But there is a way to work around this hurdle and improve the code so that one may avoid this needless error. Just change matchPhrase() as follows:
function matchPhrase(number, awesomePhrases){
awesomePhrases = typeof awesomePhrases !== 'undefined' ? awesomePhrases : "";
for(var i = 0, max=awesomePhrases.length; i < max; i++){
if(number == awesomePhrases[i]){
return true;
}
}
return false;
}
The first statement accepts the second argument's value as long as it is not the undefined value; if so, then the variable gets set to the empty string. (Source for technique: here).
To make the code more readily comprehensible, I suggest rewriting allTests() as follows, so that the code follows a more explicit self-documenting style:
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros( arrDigits ) || sameDigits( arrDigits ) || incrementing( arrDigits ) || decrementing( arrDigits) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
This function takes a number and uses its toString() method to convert the number to a string. The resulting string which is not visible will split itself on the empty string so that the result of arrDigits is an array of numerical strings, each one consisting of just one digit. This is the point of origin for the ensuing problem with allZeros() which compares a stringified digit with a number.
Incidentally, in the function allTests() there is an awfully lengthy ternary expression. The syntax is fine, but you might wish to rewrite the code as follows:
function getCriteriaStatus(arrDigits,number,awesomePhrases) {
var criteria = new Array();
criteria[0] = allZeros( arrDigits );
criteria[1] = sameDigits( arrDigits );
criteria[2] = incrementing( arrDigits );
criteria[3] = decrementing( arrDigits);
criteria[4] = palindrome(number);
criteria[5] = matchPhrase(number, awesomePhrases);
var retval = false;
for (var i=0, max=6; i < max; i++) {
if ( criteria[i] == true ) {
retval = true;
break;
}
}
return retval;
}
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
var criteria_met = getCriteriaStatus(arrDigits,number,awesomePhrases);
return (number > 99 && criteria_met);
}
To obtain the desired true result from allTests() when it invokes allZeros(), rather than complicate the code by using parseInt(), I suggest rewriting allZeros() and any other functions containing code that compares a numerical string value with a number by changing from the identity operator to the equality operator. The change involves merely replacing === with == as well as replacing !== with !=. The code that compares values of the same data type, using the identity operators, those operators may, and probably should, remain unchanged. (See here).
This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 5 years ago.
How to convert a string to Boolean ?
I tried using the constructor Boolean("false"), but it's always true.
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).
var myBool = myString == "true";
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
you can also use JSON.parse() function
JSON.parse("true") returns true (Boolean)
JSON.parse("false") return false (Boolean)
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return true
else
return false
You can't use Boolean as you think.
trick string to boolean conversion in javascript. e.g.
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
I am still amazed how people vote blindly for solutions that won't work, like:
var myBool = myString == "true";
The above is so BUGGY!!!
Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!
Alternative
var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!
will always evaluate right!
Depends on what you see as false in a string.
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
I believe the following code will do the work.
function isBoolean(foo) {
if((foo + "") == 'true' || (foo + "") == 'false') {
foo = (foo + "") == 'true';
} else {
console.log("The variable does not have a boolean value.");
return;
}
return foo;
}
Explaining the code:
foo + ""
converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.
(foo + "") == 'true'
This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.
(foo + "") == 'true' || (foo + "") == 'false'
Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.
In the 3rd line, the value of 'foo' is finally "converted" to boolean.
These lines give the following output:
Boolean(1).toString(); // true
Boolean(0).toString(); // false
Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#.
So workaround is
var setActive = 'true';
setActive = setActive == "true";
if(setActive)
// statements
else
// statements.
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
See this question for reference:
How can I convert a string to boolean in JavaScript?
There are a few ways:
// Watch case sensitivity!
var boolVal = (string == "true");
or
var boolVal = Boolean("false");
or
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
You can try this:
var myBoolean = Boolean.parse(boolString);