array of arrays: infinite loop [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am dynamically adding/removing elements using javascript & jQuery. For some reason my inner for loop is not exiting. The counter continues to climb past the arrays length, and continues to add elements until the browser crashes. When stepping through in Firefox debugger groupList[i].length shows the correct value.
Any ideas why the internal loop never returns false?
var $j = jQuery.noConflict();
// array of arrays
var groupList = [];
groupList[groupList.length] = ["Japan", "Honda", "Toyota", "Nissan"];
groupList[groupList.length] = ["America", "Ford", "Dodge", "Chevrolet"];
// loop that creates a radio button from the first element in each array
for (var i = 0; i < groupList.length; ++i) {
$j("#groupBtns").append("<label class=\"btn btn-primary active\" id=\"btn" +
groupList[i][0] + "\"><input type=\"radio\">" + groupList[i][0] + "</label>");
}
// function to add second group of radio button for remaining elements in selected array
function groupClick(group) {
for (var i = 0; i < groupList.length; ++i) {
if (group == groupList[i][0]) {
// -- this is the infinite loop -- //
for (var o = 1; 0 < groupList[i].length; ++o) {
$j("#subGroupBtns").append("<label id=\"btn" + groupList[i][o] +
"\" class=\"btn btn-primary\"><input type=\"radio\">" +
groupList[i][o] + "</label>");
}
}
}
}
// event listener
$j("#groupBtns").on('click', function (e) {
groupClick($j(e.target).text())
});
note: the arrays will not always be the same length so I cannot use a static terminator for the loop.

You have a typo :
for (var o = 1; 0 < groupList[i].length; ++o) {
You are doing 0 < groupList[i].length, always resulting to true if there's a length.
Should be :
for (var o = 1; o < groupList[i].length; ++o) {

Related

I am trying to concatenate the second parameter to the first in JS [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I'm pretty stuck, It should evaluate to ["present", "pretty", "precede"]
function addTooStart(x, y) {
let a = [];
let b = "";
for (let i in x) {
a = x.push(y);
a = x[b]
}
return a
}
let abc = addTooStart(["sent", "tty", "cede"], "pre");
console.log(abc)
I'm not sure what your a and b are attempting to do here. Some problems from your code:
x.push(y) adds the element y to the end of the array x, and then returns the new length of the array, so now a is a number.
x[b] will always be an invalid call, since b equals the empty string and is never changed, arrays are integer indexed.
The general approach here would be to loop through the array x, like you did, then for each element, set it equal to "y + current element". I have attached a working version below.
function addToStart(x,y){
for (let i = 0; i < x.length; i++) {
x[i] = y + x[i]
}
return x
}
addToStart([ "sent", "tty", "cede" ], "pre"); // -> [ 'present', 'pretty', 'precede' ]

How do you execute the code inside a nested for-loop only for the instance when a condition is met? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm using a nested for-loop to compare the items in an array to other items within the same array. Once a particular condition is met concerning the items being compared, I want to discontinue the loop and push those two items into a different array. The problem is, however, that when the condition is met it will push those two items into the array for the number of iterations in the nested loop. How would I go about only pushing those items into the new array for the one time the condition is met?
I've already attempted to break out of the initial for-loop but this doesn't seem to do anything.
outer_loop:
for (let i = 0; i < varifiedKeypoints.length; i++) {
let initialKeypoint = varifiedKeypoints[i];
for (let j = 0; j < varifiedKeypoints.length; j++) {
let comparisonKeypoint = varifiedKeypoints[j];
if (initialKeypoint.part != comparisonKeypoint.part) {
if (Math.abs(comparisonKeypoint.position.x - initialKeypoint.position.x) <= 20
&& Math.abs(comparisonKeypoint.position.y - initialKeypoint.position.y) <= 20) {
if (keypointsCompatible(initialKeypoint.part, comparisonKeypoint.part)) {
console.log("Activating part: " + initialKeypoint.part);
console.log("Activated part: " + comparisonKeypoint.part);
let keypointPair = {
point_1: initialKeypoint.part,
point_2: comparisonKeypoint.part
}
console.log("Pushing parts!");
activeParts.push(keypointPair);
console.log("breaking loop!");
break outer_loop;
console.log("Loop broken - NOT!!!")
}
}
}
}
}
Add this above your first for loop
outer_loop:
Then in your condition break out with
break outer_loop;

Storing DOM element reference in JavaScript Array. Why cant I reuse stored reference to add eventListener? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm afraid it might be a silly question, but I have no idea what occurs my problem.
I dynamically create buttons (each button has unique id), and I store each btn reference (document.getElementById()) in simple two-dimensional array. All these because i need to hold btns in well organized structure.
The problem is: when i try to modify element by reference previously stored in my array, there appears to be no connection between ref and html element.
var Table = {
size: 10,
table: [],
generateTable: function() {
var i = 0,
j = 0,
id = null,
tablePlaceholder = document.getElementById("tableHTML");
//Generate table
for (i = 0; i < this.size; i++) {
this.table.push([]);
for (j = 0; j < this.size; j++) {
id = i.toString() + "-" + j.toString();
tablePlaceholder.innerHTML += element(id);
this.table[i].push(document.getElementById(id));
}
tablePlaceholder.innerHTML += "</br>";
}
console.log(this.table[0][0].className);
document.getElementById("0-0").className += " btn-success";
console.log(this.table[0][0].className);
}, ...
Results of last two console.logs is the same, but element has changed in DOM.
table[0][0] returns same content as document.getElementById("0-0").
(element() function returns simple html code (it works well))
innerHTML += '<div>...</div>';
This could break references to already constructed DOM elements and cause other chaos. In reality, all you want to do is append a single new element to the end.
var elem = document.createElement('div');
elem.id = id;
tablePlaceholder.appendChild(elem);​​​​​​​​​​​​​​​​

Iterate two arrays: Cannot read property 'length' of undefined [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I want to iterate over two arrays, states and districts, but I get an error-message saying "Cannot read property 'length' of undefined". I don't know what's causing it.
This is my code:
var estados = [ "aguascalientes", "baja-california", "baja-california-sur",
"yucatan", "zacatecas", ];
var municipios = [ [ "aguascalientes", "asientos", "calvillo", "cosio", "tepezala" ],
[ "mexicali", "playas-de-rosarito", "ensenada" ] ];
$("#property_location").change(function () {
$( "#property_location option:selected" ).each(function() {
var i;
var j;
for (i = estados.length - 1; i >= 0; i--) {
if ($( this ).val() == estados[i]) {
console.log(estados[i]);
for (j = municipios[i].length - 1; i >= 0; i--) {
$("#property_municipio option[value='"+municipios[i][j]+"']").show();
}
} else {
for (j = municipios[i].length - 1; i >= 0; i--) {
$("#property_municipio option[value='"+municipios[i][j]+"']").hide();
}
}
}
});
}).change();
Your problem is that estados has more member than municipios you loop trough every member of estados and check how many member does the municipios sub array have.
for (j = municipios[i].length - 1; i >= 0; i--)
if i is greater than 1 municipios[i] is undefined and you can't calculate the length of undefined. this generate your error.
By the way, you overwrite your loop index i if you use it in both loops.
Please use it like that:
for(var i = 0; i < array.length; i++){
...
for(var j = 0; j < array.length; j++){
...
}
}
The first/top array is having 5 elements as I see, while the second array municipios is having 2 elements( ofcourse the nested lists are having data, but the actual length will be 2 as is it containing only 2 lists).
While the outer loop is working fine, the issue is with the inner loop. When i reaches greater than 2, suppose 3, the code is trying to fetch the 3rd element from municipios array, which does not even exist. Moreover, its trying to access that particular elements' length.

Javascript - Passing from a DOM element to array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Hello and thank you for your time.
Here is the code :
<script>
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0, c = names.length ; i < c ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);// the results are : undefined
}
</script>`
I've tried to use the method tostring, or to push the results into the array but without success.
Thanks
Your main issue seems to be fixed. Make sure the DOM has been loaded before you try to run your code, and there is no need for two variables in your loop. Simplify it like below:
window.onload = function () {
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0 ; i < names.length ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);
}
};
Fiddle
ar.length equals 0, because you just declare the array, but dont put anything into it. I think what you wanted to do is the following:
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0 ; i < names.length ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);
}

Categories

Resources