How to construct a string which will pass if(variable) - javascript

I'm a jquery novice. I've boiled my code down to the simplest way to describe my problem. But I am having trouble wording it.
if(var1 && var2){
// this works
}
searchMe = var1+" && "+var2;
if(searchMe){
// this doesn't work
}
searchMe = "var1"+" && "+"var2";
if(searchMe){
// still doesn't work
}
I would like to be able to construct that "searchMe" variable based on user input. Can someone tell me a better way to do this? Thanks!

Not sure but you can make use of eval function
if(eval(searchMe)){
// this doesn't work
}

A possible way to do this without the dreaded eval (which really, you should never use) is to just evaluate as you go, and then end up with one variable at the end which is boolean.
var a = true;
var b = a && (false || true) && (1 < 2);
if (b)
document.write('yes');
else
document.write('no');
var c = b && false;
document.write(', ');
if (c)
document.write('yes');
else
document.write('no');
To relate it to your example
searchMe = var1 && var2;
if(searchMe){
// this does work
}

Related

JS OR statement just not working

I know this question has been asked a million times but I've gone through just about every method suggested in other threads and cannot seem to figure out why the OR statement in my IF is not working. And would like some explanation as to how to use the OR function if I am doing this completely wrong.
I have the following code
if((a != 'error') || (a != 'stay')) {
//Do something here
}
And regardless if the a is error or stay the code is being executed anyway
I have also tried
if((!a == 'error') || (!a == 'stay')) {
//Do something here
}
And without brackets, but noting seems to work.
Thanks in advance
Your condition is a tautology. It's true no matter what the value of a is. If a is 'error' then a is not 'stay' and vice versa. It seems like what you want is
if (a != 'error' && a != 'stay') { /* ... */ }
You are including the (!) sign together in the brackets which is an error and will not make the logical operator work. You need to put the (!) sign outside and before the bracket. Check this code below for more clarity.
var a = "hello";
var b = "stay";
var c = "error";
if(!(a == 'error') || !(a == 'stay')) {
console.log("Hello");
};
for best practice, you should have it like this
var a = "hello";
var b = "stay";
var c = "error";
if(!(a == 'error' || a == 'stay')) {
console.log("Hello");
};

Need help in converting C++ to javascript

I'm constructing a javascript indicator for my client and they gave me below C++ code from their old system. I have never done C++ program before. Below is the part of the C++ code. What I want to know is in the line
if (it3 != d1Swing.end() && it3->x == h[i].x) --(it1 = it2 = it3); what is the meaning of --(it1 = it2 = it3)? What will it looks like in javascript?
vector<PTPoint::PTIndexPoint> dnSwing;
list<PTPoint::PTIndexPoint> hq, lq;
vector<PTPoint::PTIndexPoint>::iterator it1 = d1Swing.begin(), it2 = d1Swing.begin(), it3 = ++d1Swing.begin();
//
// more code here
//
for (int i = 0; i < period; ++i)
{
while (!hq.empty() && hq.back().y < h[i].y) hq.pop_back();
hq.push_back(h[i]);
while (!lq.empty() && lq.back().y > l[i].y) lq.pop_back();
lq.push_back(l[i]);
if (it3 != d1Swing.end() && it3->x == h[i].x) --(it1 = it2 = it3);
//
// more code here
//
}
//
// more code here
//
p->swap(dnSwing);
Thanks in advance.
tslin
It means that their previous programmer loved being "clever".
The value of an assignment is a reference to the object that was assigned to, and assignment associates to the right.
--(it1 = it2 = it3)
is
--(it1 = (it2 = it3))
and it's intended to assign the value of it3 to it2 and it1, then decrement it1.
(I have a hunch that this may be undefined, which is a thing that happens frequently when you're being clever in C++.)
it1 is apparently intended to be "one step behind" it2.
A more reasonable way to write that is
it2 = it3;
it1 = it2 - 1;
(In JavaScript, I suspect that you need to work with array indices rather than iterators to accomplish the same thing.)

Faster and shorter way to check if a cookie exists

What is the shorter and faster way to know if a cookie has a value or exists?
I'm using this to know if exists:
document.cookie.indexOf('COOKIENAME=')== -1
This to know if has a value
document.cookie.indexOf('COOKIENAME=VALUE')== -1
Any better? Any problems on this method?
I would suggest writing a little helper function to avoid what zzzzBov mentioned in the comment
The way you use indexOf, it would only evaluate correct if you check for the containment of a String in a cookie, it doesn't match a complete name, in that case the above would return false therefore giving you the wrong result.
function getCookie (name,value) {
if(document.cookie.indexOf(name) == 0) //Match without a ';' if its the firs
return -1<document.cookie.indexOf(value?name+"="+value+";":name+"=")
else if(value && document.cookie.indexOf("; "+name+"="+value) + name.length + value.length + 3== document.cookie.length) //match without an ending ';' if its the last
return true
else { //match cookies in the middle with 2 ';' if you want to check for a value
return -1<document.cookie.indexOf("; "+(value?name+"="+value + ";":name+"="))
}
}
getCookie("utmz") //false
getCookie("__utmz" ) //true
However, this seems to be a bit slow, so giving it an other approach with splitting them
Those are two other possibilities
function getCookie2 (name,value) {
var found = false;
document.cookie.split(";").forEach(function(e) {
var cookie = e.split("=");
if(name == cookie[0].trim() && (!value || value == cookie[1].trim())) {
found = true;
}
})
return found;
}
This one, using the native forEach loop and splitting the cookie array
function getCookie3 (name,value) {
var found = false;
var cookies = document.cookie.split(";");
for (var i = 0,ilen = cookies.length;i<ilen;i++) {
var cookie = cookies[i].split("=");
if(name == cookie[0].trim() && (!value || value == cookie[1].trim())) {
return found=true;
}
}
return found;
};
And this, using an old for loop, which has the advantage of being able to early return the for loop if a cookie is found
Taking a look on JSPerf the last 2 aren't even that slow and only return true if theres really a cookie with the name or value, respectively
I hope you understand what i mean
Apparently:
document.cookie.indexOf("COOKIENAME=VALUE");
For me, is faster, but only slightly.
As the test shows, surprisingly, it's even faster to split the cookie up into arrays first:
document.cookie.split(";").indexOf("COOKIENAME=VALUE");
I use Jquery cookie plugin for this.
<script type="text/javascript" src="jquery.cookie.js"></script>
function isCookieExists(cookiename) {
return (typeof $.cookie(cookiename) !== "undefined");
}

A jQuery 'if' condition to check multiple values

In the code below, is there a better way to check the condition using jQuery?
if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
Unless there are other concerns, like if you will reuse the #test1, ... fields for more processing, yours should be good.
If you will fetch any of the values again to do something I would recommend storing the $('#test1') result in a variable so that you do not need to requery the dom.
Ex:
var t1 = $('#test1');
if((t1.val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) {
t1.val('Set new value');
}
This also improves readability of the row ;)
var values = ['first_value', 'second_value', 'third_value', 'fourth_value'];
$('#test1, #test2, #test3, #test4').each(function(index, el) {
if($.inArray(this.value, values)) {
// do some job;
return false; // or break;
}
});
var c=0, b='#test', a=['first_value','second_value','third_value','fourth_value'];
for(var i=0; i<4; i++)
if($(b+i).val() == a[i])
c=1;
if (c) //Do stuff here
This will decrease your code size by 25 bytes;-)
Demo: just another idea is at http://jsfiddle.net/h3qJB/. Please let me know how it goes.
You can also do chaining like:
$('#test1, #test2, #test3, #test4').each(function(){ //...use this.value here });
It might be that De Morgan's laws gives you an idea of how to make the logic a bit more compact (although I am not sure what is the specific case or is it as simple as comparing values).
Code
var boolean1 = (($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value'))
var boolean2 = (($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
if (boolean1 && boolean2)
alert("bingo");
else
alert("buzzinga");

Is a JavaScript try-catch ignoring an expected occasional error bad practice?

In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?
try{
if(myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip) {
this.setAddress(newInfo);
}
} catch(e) {} // ignore missing args
If you expect a particular condition, your code will be easier to maintain if you explicitly test for it. I would write the above as something like
if( myInfo && newInfo
&& myInfo.person && newInfo.person
&& myInfo.person.address && newInfo.person.address
&& ( myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip
)
)
{
this.setAddress(newInfo);
}
This makes the effect much clearer - for instance, suppose newInfo is all filled out, but parts of myInfo are missing? Perhaps you actually want setAddress() to be called in that case? If so, you'll need to change that logic!
Yes. For one, an exception could be thrown for any number of reasons besides missing arguments. The catch-all would hide those cases which probably isn't desired.
I would think that if you're going to catch the exception then do something with it. Otherwise, let it bubble up so a higher level can handle it in some way (even if it's just the browser reporting the error to you).
On a related note, in IE, even though the specs say you can, you can not use a try/finally combination. In order for your "finally" to execute, you must have a catch block defined, even if it is empty.
//this will [NOT] do the reset in Internet Explorer
try{
doErrorProneAction();
} finally {
//clean up
this.reset();
}
//this [WILL] do the reset in Internet Explorer
try{
doErrorProneAction();
} catch(ex){
//do nothing
} finally {
//clean up
this.reset();
}
You could always write a helper function to do the checking for you:
function pathEquals(obj1, obj2, path)
{
var properties = path.split(".");
for (var i = 0, l = properties.length; i < l; i++)
{
var property = properties[i];
if (obj1 === null || typeof obj1[property] == "undefined" ||
obj2 === null || typeof obj2[property] == "undefined")
{
return false;
}
obj1 = obj1[property];
obj2 = obj2[property];
}
return (obj1 === obj2);
}
if (pathEquals(myInfo, newInfo, "person.name") &&
pathEquals(myInfo, newInfo, "person.address.street") &&
pathEquals(myInfo, newInfo, "person.address.zip"))
{
this.setAddress(newInfo);
}
For the example given I would say it was bad practice. There are instances however where it may be more efficient to simply trap for an expected error. Validating the format of a string before casting it as a GUID would be a good example.

Categories