Declaring a for loop function in javascript - javascript

I have a for loop that searches for a value in an array in my javascript code in couchDb. I want to make it into a function. This should be fairly simple but I am having trouble with it. This is the for loop(Which works perfectly fine):
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].address) return;
}
}
throw({forbidden: 'doc.address is required'});
And this is the way I wrapped it into a function:
function arrayReq(field, message) {
message = message || "Array must have a " + field;
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].field) return;
}
}
throw({forbidden: message});
}
I would think that the return in the function should stop the function from going any further but it still throws the error. Can someone tell me what I am doing wrong? Btw if i change field into address it works fine. Can I not make the address into a changeable variable?

I think the problem is that you are trying to use field as both a string variable, and a property of your object inside the destination[] array.
In your code, if the destination[i] object does not have a property called field (not the string value populated in the field parameter, but an actual property named "field") it will never evaluate to true and break out of the function.
To access a property of an object by using the string representation in javascript, you use the indexer syntax.
Try changing it from array.destination[i].field to array.destination[i][field]

Related

if else preventing loop for passing through object

I am having trouble returning a statement when my RegExp finds no matches :
function ai(message) {
if (username.length < 3) {
username = message;
send_message("Oh, well hello " + username + ", My name is Donald J Trump and i'm a big boy");
} else {
for (i = 0; i <= botChat.length; i++) {
var re = new RegExp(botChat[i][0], "i");
if (re.test(message)) {
var length = botChat[i].length - 1;
var index = Math.ceil(length * Math.random());
var reply = botChat[i][index];
send_message(reply);
}
}
}
}
When I enter a phrase it can correctly match the first line in an array as per the for loop. The issue I'm having is when I try to add an else statement it ceases to loop through my array properly.
I have tried :
else if (re.test(message) === false) {
send_message("i can't be expected to know everything");
}
But it doesn't work, it prevents the loop from looping past botChat[0][0].
I've also tried :
if (send_message().val() == "") {
// ...
}
But every time my code no longer works. Is there a method of adding something to my array that says 'if you don't find a match above, choose this'?
Or just a way of working my code so that the if/else works?
attached is the codepen.
I checked your codepen and the lines 190 and 194 console.log(send_message().val()); seems to be breaking the loop because those lines are throwing an exception since send_message() returns undefined and undefined does not have the .val() method.
Your regular expressions are working fine. I recommend not creating new RegExp objects every iteration, instead, use the one defined in the array if (botChat[i][0].test(message)), the overhead will be less.

Check if nested object is declared and has a value without so many conditional checks

I have a JSON object which I get from a server. The key which I get the value from looks something like this:
var myJson = data.body.region.store.customer.name;
I am trying to get the name key here, but sometimes the JSON (which comes from a service I have no control over) will have some empty fields, like for instance name might not be defined so the object will actually look like this: data.body.region.store.customer. Sometimes too customer, or store, or region might not be defined (If the data doesn't exist the service doesn't return a null or empty string for the value).
So if I need the name what I am doing is this:
if(data.body.region.store.customer.name){
//Do something with the name
}
But say even store isn't defined, it will not get the value for name(which I would expect to be undefined since it doesn't exist) and the program crashes. So what I am doing now is checking every part of the JSON before I get the value with AND operands:
if(data && data.body && data.body.region && data.body.region.store && data.body.region.store.customer && data.body.region.store.customer.name){
//Do something with the name value then
}
This works, because it checks sequentially, so it first checks does data exist and if it does it checks next if data.body exists and so on. This is a lot of conditions to check every time, especially since I use the service a lot for many other things and they need their own conditions too. So to just check if the name exists I need to execute 6 conditions which of course doesn't seem very good performance wise (and overall coding wise). I was wondering if there is a simpler way to do this?
var myJson = null;
try {
myJson = data.body.region.store.customer.name;
}
catch(err) {
//display error message
}
You can try following
function test(obj, prop) {
var parts = prop.split('.');
for(var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if(obj !== null && typeof obj === "object" && part in obj) {
obj = obj[part];
}
else {
return false;
}
}
return true;
}
test(myJson, 'data.body.region.store.customer.name');

JavaScript throws TypeError saying that my variable is undefined

I don't have much experience in JavaScript, so far I have this:
function loop() {
var authorDivs = document.getElementById('ctl00_MainContent_MCPObjectInfo_dvCreatorView').getElementsByTagName("div");
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (typeof divOfDiv.item(i) === 'undefined' || divOfDiv.item(i) === null) {
console.log("This is undefined or null");
}
else {
var realDivs = divOfDiv.item(i);
realDivs.item(i).textContent = "please work plz";
}
}
}
I get the following error from the console in FireFox: TypeError: realDivs is undefined on this line: realDivs.item(i).innerHTML = "please work plz";
Essentially what I have (in my mind) is a loop that goes through authorDivs and gets all of the divs within those divs and saves them in divOfDiv. I then check to see if the divs in divOfDiv are undefined or null, if they are not then those divs get saved in a variable realDivs which I then use to edit the innerHTML. That's what I'd ideally like to see happen, what is causing the error? What am I doing wrong?
Note: I do not have access to jQuery but only JavaScript.
Edit: I've added the changes suggested below and its fixed that -- thanks! But I'm now getting the following error: TypeError: realDivs.item is not a function
What is causing that? And on another note how do I know when I'm dealing with an array and when I'm dealing with an HTMLCollection? Do you just assume? I've never used a loosely typed language before so its new to me.
Well, you'll need to move that code inside the conditional block that is supposed to prevent it! Also, || "null" is not going to work as you expect, you'll need to check for || divOfDiv.item(i) === null explicitly.
So try
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (divOfDiv.item(i) == null) {
console.log("This is undefined or null");
} else {
var realDivs = divOfDiv.item(i)
realDivs.item(i).innerHTML = "please work plz";
console.log(divOfDiv.item(i));
}
}
However, that still doesn't really work for two reasons:
The i index you use to access the i-th divOfDiv comes from the iteration over authorDivs - hardly what you want. Instead, use a second loop over all divOfDivs.
Your realDivs variable does hold a single <div>, which does not have an .item method. You'd just directly access its .innerHTML property.
So you should use
var authorDivs = document.getElementById('authorView').getElementsByTagName("div");
for (var i=0; i<authorDivs.length; i++) {
var divsOfDiv = authorDivs.item(i).getElementsByTagName("div");
for (var j=0; j<divsOfDiv.length; j++) {
var realDiv = divsOfDiv.item(j);
realDiv.innerHTML = "please work plz";
console.log(realDiv);
}
}
it will happen in case when your if (typeof divOfDiv.item(i) === 'undefined' || 'null') returns true. Then you never initialize realDivs (what would happen if condition was falsy). Later you try to call item function on that unitialized object
There are two problems in the code.
comparing DOM object with 'undefined' and null. If div tag is not available in authorDivs[i], it will return empty DOM array. So, comparision of empty DOM array with undefined and null is not good approach. We can use array length property for doing validation.
divOfDiv = authorDivs[i].getElementsByTagName("div");
if(divOfDiv.length > 0) { console statement}
As item(i) is already return single DOM element, item(i) of "realDivs" variable is not proper approach. In addition to this, innerHTML method needs to be used after validating whether realDivs contains DOM element. Please update the code as below.
var realDivs = divOfDiv.item(i);
realDivs ? (realDivs.innerHTML = "please work plz"): null;
Note : item(i) will return null if DOM is not available.

keep add the value without overwrite the function

function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}

Validation for checkboxes

Hello
I have a JS function which says
for(var i = 0; i < document.calDailyBlock.selFilCheckBox.length; i++)
{
if(document.calDailyBlock.selFilCheckBox[i].checked)
{
filteredInitId += document.calDailyBlock.selFilCheckBox[i].value + ",";
alert(filteredInitId);
isProjCheck = true;
}
}
document.calDailyBlock.filteredComId.value = filteredInitId;
When there are no checkboxes on the page and I try to click on Filter button which calls this function, I receive an error "document.calDailyBlock.selFilCheckBox.length' is null or not an object"
Is there any simple thing which I can add in this function ?
Also can anyone help me how to check if there is only one checkbox on one page ?
Thanks in advance
I think you are relying on a fairly obscure (non-official) feature of some browsers which lets you get an element from the document as if it were an attribute. In other words, you are going:
document.calDailyBlock
This is searching the document for a variable calDailyBlock. Instead, you should use the standardised getElementById:
document.getElementById("calDailyBlock")
And use the same approach for getting selFilCheckBox.
This will return null if calDailyBlock or selFilCheckBox are not found. Before you go calling length on them (which gives that error), you should check to see if you got back null, and then (I suppose) fail silently (don't do anything).
to avoid the error use an if:
if(document.calDailyBlock.selFilCheckBox) {
for(var i = 0; i < document.calDailyBlock.selFilCheckBox.length; i++)
{ … }
}

Categories

Resources