I'm writing a compare function using objects. I know that if I have the following object - var obj{ one: "foo", two: bar"} and I want to look up a property then obj["one"] will work but obj[one] will not.
However when I do the comparison function it will correctly compare obj["one"] and obj2["one"], but when I'm trying to log it in the console the syntax obj[one] works and obj["one"] comes back as undefined. It doesn't affect the functionality of the code, but I'm confused.
var num = 2;
var num2 = 4;
var num3 = 4;
var num4 = 9;
var num5 = "4";
var obj = {here: {is: "an"}, object: 2};
var obj2 = {here: {is: "an"}, object: 2};
function deepEqual(el, el2) {
var outcome = false;
console.log("comparing " + el + " and " + el2);
if (typeof el == 'object' && typeof el2 == 'object') {
console.log("These are both objects");
if (Object.keys(el).length === Object.keys(el2).length) {
console.log("These objects have the same number of keys");
for (var x in el) {
if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
console.log("comparing " + el[x] + " with " + el2[x]);
outcome = true;
} else {
return false;
}
}
} else return false;
} else if (el === el2) {
outcome = true;
}
return outcome;
}
So the part of the code I'm talking about is
if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
console.log("comparing " + el[x] + " with " + el2[x]);
outcome = true;
} else {
return false;
}
This comes back correctly in the console as "comparing (property) with (property)". However if I write it like this
if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
console.log("comparing " + el["x"] + " with " + el2["x"]);
outcome = true;
} else {
return false;
}
It says "comparing undefined with undefined".
Any insights?
in your code el["x"] does not refer to anything. There is no property in the el object that has an "x" key
you are in a for loop which define x so you need to use that variable instead of "x"
for (var x in el) {
if (el2.hasOwnProperty(x) && el[x] === el2[x]) {
console.log("comparing " + el[x] + " with " + el2[x]);
outcome = true;
} else {
return false;
}
}
Related
Here's my function that is supposed to validate a name so that there is no duplicates:
function validateBucketName(){
var counter = 1;
var validated = false;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if(vm.buckets.length === 0) return suggestedName;
while(!validated){
var foundIndex = vm.buckets.findIndex(function (bucket) {
return bucket.name === suggestedName;
});
if(foundIndex === -1){
validated = true;
} else {
counter++;
suggestedName = "Bucket " + (vm.buckets.length + counter);
}
}
return suggestedName;
}
I am getting the pretty common error, that I am aware of how to deal with in for loops, but can't figure out how to do that with the while loop. Can someone have a look at this?
Ps. This is probably very inefficient way of trying to make sure no duplicate names exist. If you have a suggestion for how to make that better feel free to comment.
This is a better approach
You don't need the validate variable, just use while(true) because you're going to get the missing suggestedName.
When this condition if (foundIndex === -1) is true return the suggestedName.
Look this code snippet with those modifications:
function validateBucketName() {
var counter = 1;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if (vm.buckets.length === 0) return suggestedName;
var compare = function(bucket) {
return bucket.name === suggestedName;
};
while (true) {
if (vm.buckets.findIndex(compare) === -1) {
return suggestedName;
else
suggestedName = "Bucket " + (vm.buckets.length + (counter++));
}
return suggestedName;
}
I'm using an existing web app created using vue.js. and below is the code.
function () {
var e = this,
t = e.$createElement,
n = e._self._c || t;
return e.message.text && "human" === e.message.type ? n("div", {
staticClass: "message-text"
}, [e._v("\n " + e._s(e.message.text) + "\n")]) : e.message.text && e.shouldRenderAsHtml ? n("div", {
staticClass: "message-text",
domProps: {
innerHTML: e._s(e.botMessageAsHtml)
}
}) : e.message.text && "bot" === e.message.type ? n("div", {
staticClass: "message-text"
}, [e._v("\n " + e._s(e.shouldStripTags ? e.stripTagsFromMessage(e.message.text) : e.message.text) + "\n")]) : e._e()
}
and here is my n function
function l(e, t) {
function n(e, t, n, i) {
console.log(typeof e + "\t" + typeof t + "\t" + typeof n + "\t" + typeof i);
return function () {
if (n in t) {
return function () {
if (i && "object" === He()(e[n])) {
return f()({}, l(t[n], e[n], i), l(e[n], t[n], i));
}
return function () {
if ("object" === He()(e[n])) {
return f()({}, e[n], t[n]);
}
return t[n];
}();
}();
}
return e[n];
}();
}
var i = arguments.length > 2 && void 0 !== arguments[2] && arguments[2];
return k()(e).map(function (r) {
var o = n(e, t, r, i);
return Ke()({}, r, o);
}).reduce(function (e, t) {
return f()({}, e, t);
}, {});
}
The above code basically creates a div tag with class name as message-text, I want to create a span inside this div. I am not at all good with vue.js and the code seems pretty confusing. please help me out in creating a span inside this div.
This looks like a compiled code and minified probably. But if you can't get the uncompiled version I would try and simplify the code as it has a spaghetti if else.
function(){
var e = this,
t = e.$createElement,
n = e._self._c || t,
result;
if(e.message.text && "human" === e.message.type){
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.message.text) + "\n")])
}else{
if(e.message.text && e.shouldRenderAsHtml){
result = n("div", {staticClass: "message-text",domProps: {innerHTML: e._s(e.botMessageAsHtml)}})
}else{
if(e.message.text && "bot" === e.message.type){
if(e.shouldStripTags){
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.stripTagsFromMessage(e.message.text)) + "\n")])
}else{
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.message.text) + "\n")])
}
} else {
result = e._e();
}
}
}
return result;
}
You probably need to look into function n which is taking the arguments "div" as string and css class as object "message-text" with other props like innerHTML...
I have created the following if else statement but there are so many if else statement. I want to learn how can I make it shorthand?
if(REL == 'Like'){
$('#Like' + dataid).attr('rel', 'NotLike');
} else if(REL == 'Love') {
$('#Love' + dataid).attr('rel', 'NotLove');
} else if(REL == 'Unbelievable'){
$('#Unbelievable' + dataid).attr('rel', 'NotUnbelievable');
} else if(REL == 'Spectacular'){
$('#Spectacular' + dataid).attr('rel', 'NotSpectacular');
} else if(REL == 'Emotional'){
$('#Emotional' + dataid).attr('rel', 'NotEmotional');
}
Just take the variable with a check.
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(REL) !== -1) {
$('#' + REL + dataid).attr('rel', 'Not' + REL);
}
For a flip-flop based on strings starting with 'Not', you may use this
var temp = REL,
not = 'Not';
if (REL.substring(0, 3) === 'Not') {
temp = REL.substring(3);
not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
$('#' + REL + dataid).attr('rel', not + temp);
}
Proposal with state saver
var lastState = '';
function change(state) {
var temp = state,
not = 'Not';
if (state.substring(0, 3) === 'Not') {
temp = state.substring(3);
not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
$('#' + temp + dataid).attr('rel', not + temp);
}
return not + temp;
}
// usage always both together:
change(lastState); // to reset the last state
lastState = change(REL); // call change and save the actual state
I inherited a javascript code base and I am new to javascript. So i am using JSHint to avoid common mistakes, misuses.
JSHint has found this piece of code but i do not know how to avoid the evil eval:
function GetProperties(object) {
var result, property, t;
result = '';
for (property in object) {
if (property.indexOf('Get', 0) === 0) {
t = object[property] + "...";
eval("if (GetNumOfParameter(t) == 0) var m = object." + property + "(); else var m = -100;");
if (window.m != -100) {
result += property + ': ' + window.m + '\r\n';
}
}
}
return result;
}
Use the following, it's far better, you don't need to use m if you don't use it anywhere else.
function GetProperties(object) {
var result, property, t;
result = '';
for (property in object) {
if (property.indexOf('Get', 0) === 0) {
t = object[property] + "...";
if (GetNumOfParameter(t) == 0)
result += property + ': ' + object[property]() + '\r\n';
}
}
return result;
}
AddPatient = {};
if(GenderValue === undefined) {
AddPatient.Gender = ' ';
} else {
AddPatient.Gender = GenderValue;
}
if(DateOfBirthValue === undefined) {
AddPatient.DateOfBirth = ' ';
} else {
AddPatient.DateOfBirth = DateOfBirthValue;
}
if(SSNValue === undefined) {
AddPatient.SSN = ' ';
} else {
AddPatient.SSN = SSNValue;
}
if(RaceValue === undefined) {
AddPatient.Race = ' ';
} else {
AddPatient.Race = RaceValue;
}
if(ReligionValue === undefined) {
AddPatient.Religion = ' ';
} else {
AddPatient.Religion = ReligionValue;
}
if(CellPhoneValue === undefined) {
AddPatient.CellPhoneNumber1 = ' ';
} else {
AddPatient.CellPhoneNumber1 = CellPhoneValue;
}
if(HomePhoneValue === undefined) {
AddPatient.phonenumber1 = ' ';
} else {
AddPatient.phonenumber1 = HomePhoneValue;
}
if(PrimaryPhoneValue === undefined) {
AddPatient.PrimaryPhoneNumber = ' ';
} else {
AddPatient.PrimaryPhoneNumber = PrimaryPhoneValue;
}
if(EmailValue === undefined) {
AddPatient.EmailAddress1 = ' ';
} else {
AddPatient.EmailAddress1 = EmailValue;
}
AddPatient.ResidentialAddress = {};
if(AddressValue === undefined) {
AddPatient.AddressLine1 = ' ';
} else {
AddPatient.ResidentialAddress.AddressLine1 = AddressValue;
}
if(CityValue === undefined) {
AddPatient.City = ' ';
} else {
AddPatient.ResidentialAddress.City = CityValue;
}
if(StateValue === undefined) {
AddPatient.State = ' ';
} else {
AddPatient.ResidentialAddress.State = StateValue;
}
if(ZipValue === undefined) {
AddPatient.PostalCode = ' ';
} else {
AddPatient.ResidentialAddress.PostalCode = ZipValue;
}
Is there any better way to write the same code?
You can write
AddPatient.Gender = GenderValue || " ";
The || operator returns the left-most "truthy" operand, so this will evaluate to " " if GenderValue is "falsy" (such as undefined, false, "", 0, or null)
function isDefined(value){
if(value != null)
return value;
else
return ' ';
}
AddPatient = {};
AddPatient.Gender =isDefined(AddPatient);
and son on
Here is a suggestion to what you actually asked:
http://jsfiddle.net/mplungjan/b5yRw/
It will of course work with a form instead.
var GenderValue = "F";
var DateOfBirthValue; // undefined
var AddressValue = "some street";
// var CityValue; // undeclared
function addItem(obj,varName) {
obj[varName] = window.hasOwnProperty(varName+"Value")?window[varName+"Value"]||"not set":"not declared";
}
function addItemLoop(obj) {
for (var o in obj) {
if (typeof obj[o] === 'object') {
addItemLoop(obj[o]);
}
else {
addItem(obj, o);
}
}
}
AddPatient = {
Gender : " ",
DateOfBirth: " ",
ResidentialAddress : {
Address:" ",
City: " "
}
}
addItemLoop(AddPatient);
document.write("<br/>Gender (F):"+AddPatient.Gender);
document.write("<br/>DOB (not set):"+AddPatient.DateOfBirth);
document.write("<br/>ResidentialAddress Address (some street):"+AddPatient.ResidentialAddress.Address);
document.write("<br/>ResidentialAddress City (not declared):"+AddPatient.ResidentialAddress.City);
Previous answer
Not better but shorter using the ternary operator
AddPatient.Gender = (GenderValue === undefined)? " ":GenderValue;
or shortcut
AddPatient.Gender = GenderValue || " ";
Note - In the shortcut you WILL get a space if value is 0
In EITHER you will get an error if GenderValue has not been declared.
So somewhere you need a var GenderValue;
Example:
var b="hello", c;
var a = {}
a.x = b||"no b"
a.y = (c===undefined)? "no c here":c
a.z = c || "no c here either"
alert(a.x)
alert(a.y)
alert(a.z)
Here's one option:
function SetOrDefault(value, property) {
if (typeof(value) == 'undefined' || value == null) {
property = ' ';
}
else {
property = value;
}
}
And then call it like this:
SetOrDefault(GenderValue, AddPatient.Gender);