For loop in Javascript runs only once - javascript

Here is my code. I do not quite understand why the for loop runs only once, both inner and outer. nodeList.length and innerNodeList.length show appropriate values when I generate alert messages. I see that both i and j do not increment beyond 0. Kindly point out anything wrong with the code.
function getCategoryElements() {
var newCategoryDiv = document.getElementById("category");
var nodeList = newCategoryDiv.childNodes;
for (var i = 0; i < nodeList.length; ++i) {
var innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (var j = 0; j < innerNodeList.length; ++j) {
if (innerNodeList[j].nodeName == "SELECT") {
alert("inside select Node value " + innerNodeList[j].nodeValue.toString());
document.getElementById("newCategories").value =
document.getElementById("newCategories").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
} else if (innerNodeList[j].nodeName == "TEXTAREA") {
document.getElementById("newCategoriesData").value =
document.getElementById("newCategoriesData").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
}
}
}
}

var newCategoryDiv, nodeList, innerNodeList, innerNode, i, j;
newCategoryDiv = document.getElementById("category");
nodeList = newCategoryDiv.childNodes;
for (i = 0; i < nodeList.length; ++i) {
innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (j = 0; j < innerNodeList.length; ++j) {
innerNode = innerNodeList[j];
if (innerNode.nodeName === "SELECT") {
alert("inside select Node value " + innerNode.nodeValue.toString());
document.getElementById("newCategories").value += '<%=delimiter%>' + innerNode.nodeValue;
} else if (innerNode.nodeName === "TEXTAREA") {
document.getElementById("newCategoriesData").value += '<%=delimiter%>' + innerNode.nodeValue;
}
// Will this work?
alert('Does this alert appear');
}
}
I took the liberty to refactor your code and clean it up a little bit. In case you're not aware, all variables have function scope in Javascript, so no matter where you declare them within a single function, Javascript treats them as if the variable declaration is the first statement.
It appears that your code is syntactically correct, and so I think that the most logical place to look for a problem is that there could be an error occurring after the last alert function call.
In order to check this, try adding another alert function call to the end of the inner loop. If it doesn't run, you'll know this is the case.

Related

How to update all child IDs using plain JavaScript

I have a JavaScript function called resetIndex. It works fine but I want to reset all child IDs. How can I do this? Is there any method like firstChild and lastChild?
I'm new with JavaScript. Can anyone help?
I have following function:
function resetIndex(delId) {
for (var i = delId + 1; i < count; i++) {
var currentElement = document.getElementById(i);
currentElement.id = i - 1;
var update = currentElement.childNodes;
update.setAttribute('id', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
You can use
node.children[0]
to get the first one, and
node.children[node.children.length - 1]
to get the last one.
Make sure to check if they exist, first.
To do something to all child-nodes, you can use a for-loop, like
for(let a = 0; a < node.children.length; a++) {
node.children[a].id = "my-new-id";
}

Getting 'undefined', can't figure out why

Working my way through 'Eloquent Javascript' and I'm hitting a bit of a roadblock in understanding how to properly use if with for statements in the language. I'm supposed to write a function that counts all instances of the uppercase 'B' in a given string. The code I've written thus far:
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {}
counter += 1;
}
}
console.log(countBs("BBC"));
expected output: 2
actual output: undefined
Is my loop going wrong, or my 'if'?
You have two bugs
You are incrementing your counter outside of the if statement.
You have no return statement.
The following can be used:
function countBs(s){
var counter = 0;
for(i = 0; i < s.length; i++){
if ('B' == s.charAt(i)) {
counter += 1; // this needs to be inside the if statement
}
}
return counter;
}
Your function does not have a return statement.
A few issues.
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {
++counter;
}
}
return counter;
}
document.write(countBs("BBC"));
You were not returning counter at the end of the function
Your if statement was opened, then immediately closed, so nothing happens if the character was B
Even if you returned counter and fixed the above 2 errors, the function still would have exited after 1 B was found. To fix this, move the return after the for ends.
If you're interested, the same problem can be solved with this one-liner:
function countBs(s) {
return s.match(/B/g).length;
}
document.write(countBs("BBC"));
Which finds all B characters (case-sensitive), puts them into an array, then returns how many items are in that array.

Short way to write a long series of if-else-if's?

How to do two variables in an if condition? Here I have few else ifs and I want a 100 else ifs! Is there a shorter way?
$(document).on('click', '.btn-next', function () {
var z = [];
var recipientsArray = z.sort();
var zDuplicate = [];
$('option:selected.exclude_global').each(function() {
z.push($(this).val())});
for (var i = 0; i < recipientsArray.length - 1; i++) {
if (recipientsArray[i + 1] == recipientsArray[i]) {
zDuplicate.push(recipientsArray[i]);
}else if(recipientsArray[i + 2] == recipientsArray[i]){
zDuplicate.push(recipientsArray[i]);
}else if(recipientsArray[i + 3] == recipientsArray[i]){
zDuplicate.push(recipientsArray[i]);
}else if(recipientsArray[i + 4] == recipientsArray[i]){
zDuplicate.push(recipientsArray[i]);
}
}
if(zDuplicate.length>>0){
alert("Global Filter Already Exists");
event.preventDefault();
}
});
Here I have few else ifs and I want a 100 else ifs! Is there a shorter way? I have a dynamic table with dynamic rows. when my table has 5 rows the code is working, but when I have more its not working.
What you're looking for is called a nested loop. You basically can write a loop within a loop. (As many as you want, actually. Though it can get ugly fast.)
Consider your loop structure:
for (var i = 0; i < recipientsArray.length - 1; i++) {
// check if recipientsArray[i] equals any other element
}
Well, that's just another loop:
for (var i = 0; i < recipientsArray.length - 1; i++) {
for (var j = i + 1; j < recipientsArray.length - 1; j++) {
if (recipientsArray[j] == recipientsArray[i]) {
zDuplicate.push(recipientsArray[i]);
break;
}
}
}
Note that there's probably a more efficient way of checking for duplicates. (Especially if the collection is sorted.) At the very least I've changed the logic so you're not re-comparing comparisons you've already made. (I did this by starting the inner loop at i + 1 instead of 1 as your logic does.)
I also think I've replicated your else if results by using a break statement. Since your else if logic basically means "once you find one, stop looking". That's what this break should do, or at least is intended to do, but you'll want to test that. If it doesn't (nesting can be confusing sometimes, which is why it should be done carefully) then you can probably make use of labels to achieve the same effect.
Ultimately, however you implement it, the concept is the same. You're asking how to iterate over multiple values in an array. That's what a loop is for.
I don't know that language. But data and control structures are data and control structures in any language.
Substitute your for loop by :
for (var i = 0; i < recipientsArray.length - 1; i++) {
for ( var j = i+1; j < recipientsArray.lenght-1; j++) {
if (recipientsArray[i] == recipientsArray[j]) {
zDuplicate.push(recipientsArray[i]);
break;
}
}
}
Thank you so much for the idea!
A small change to your code works like heaven!
for (var i = 0; i < recipientsArray.length - 1; i++) {
for (var j = 1; j < 100; j++) {
if (recipientsArray[i+j] == recipientsArray[i]) {
zDuplicate.push(recipientsArray[i]);
break;
}
}
}

array search / for loop

I've currently got a implementation which loops through an array within a json document (returned from mongoose) and looks for specific items as below
So what's happening is i'm passing an id in the request header to express and what i need to happen is for it to grab the associated story.users.id.name from the story.users array is returned and then once it has the name send do something with all the other items in the array.
I did try to do this like below:
for (var i = 0; i < story.users.length; i++) {
if (story.users[i].id._id == req.headers.id) {
var name = story.users[i].id.name
} else {
push.apns(story.users[i].id._id, name + " started a new story");
}
}
Where it would loop through grab the name and then do something with all the other users in the array, however sometimes the else argument fires first so the name variable is undefined.
So i resorted to running two if loops after each other like below:
for (var i = 0; i < story.users.length; i++) {
if (story.users[i].id._id == req.headers.id) {
var name = story.users[i].id.name
}
};
for (var i = 0; i < story.users.length; i++) {
if (story.users[i].id._id == req.headers.id) {
} else {
push.apns(story.users[i].id._id, name + " started a new story");
}
}
But there must be a better way to the above rather than looping through an array twice?
What you do looks like the right solution (with the goal you seem to have). There's no real simple way to do only one loop.
You could make it faster and cleaner, though :
var name; // this is just cleaner than to define it in the loop
for (var i = 0; i < story.users.length; i++) {
if (story.users[i].id._id == req.headers.id) {
name = story.users[i].id.name;
break; // don't loop over the other elements
}
};
for (var i = 0; i < story.users.length; i++) {
if (story.users[i].id._id !== req.headers.id) {
push.apns(story.users[i].id._id, name + " started a new story");
}
}

Loop that finds a word in a string

So, i'm working on a 'for' loop that will identify my name, Andrew, and push it into an array, but there's something wrong with it
/*jshint multistr:true */
var text = ("Andrew is really awesome and Andrew should be working on the project, but there is honestly nothing for Andrew to do.");
var myName = ("Andrew");
var hits = [];
for (var i = 0; i < text.length; i ++) {
if (text[i] === "A") {
for (var j = i; i + nyName.length; i ++) {
hits.push(text[j]);
}
}
}
Also, the second loop is supposed to stop when it reaches the end of myName.
You're using JSHINT, so just read the error messages and it'll tell you exactly what's wrong.
Errors:
Line 7: for (var j = i; i + nyName.length; i ++) {
'nyName' is not defined.
Line 3: var myName = ("Andrew");
'myName' is defined but never used.
JSHINT isn't much good if you don't pay attention to what it's telling you.
Also, your inner loop looks odd.
for (var j = i; i + nyName.length; i ++) {
Seems like it'll cause an infinite loop. You're perhaps wanting j with a different condition.
You misspelled myName in your for loop syntax and typed nyName instead, so chances are the script dies as soon as it hits that line.
A typo in the for loop that wants to refer to myName would appear to be a big problem:
for (var j = i; i + nyName.length; i ++)
^
The misspelled myName isn't the only part that fails. You for loop will never end the loop because i + myName.length will always evaluate to true. You also need to increase the value of j or it will always get the character at index i.
Here's the corrected loop.
for (var i = 0; i < text.length; i ++) {
if (text[i] === "A") {
for (var j = 0; j < myName.length; i++, j++) {
hits.push(text[i]);
}
}
}

Categories

Resources