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

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.

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 to run a For loop using a variable with value determined by prompt [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 1 year ago.
Improve this question
Basically:
a normal for loop would be:
for (var i = 0; i < 5; i++) {
something here }
BUT my code/for loop are like this:
var numberPeople = parseInt(prompt("How many people are there?"));
for (var numberPeople = 0; numberPeople >=0; numberPeople++) {
people.names.push(prompt("Please enter the person's name", "")); }
I need to use the number entered in the first prompt, which fills the variable numberPeople to determine how many times the for loop sends a prompt asking for the names.
The problem seems to be in the for loop condition.
You are re-initializing the numberPeople variable to 0 which is why the loop doesn't work. You need to set another variable, for example, i to keep track of the iterations in the loop.
var numberPeople = parseInt(prompt("How many people are there?"));
for (var i = 0; i < numberPeople ; i++) {
people.names.push(prompt("Please enter the person's name", ""));
}
var numberPeople = parseInt(prompt("How many people are there?"));
var people = {names: []}
for (var i = 0; i < numberPeople; i++) {
people.names.push(prompt("Please enter the person's name", ""));
}
Just initialize the people variable with the object with the names property.
in your for loop, you are initialising another variable called numberPeople, which is being used as opposed to the numberPeople you set with the parseInt.. so why not looping it like this?
var numberPeople = parseInt(prompt("How many people are there?"));
for (var i = 0; i < numberPeople; i++) {
people.names.push(prompt("Please enter the person's name", "")); }

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;

array of arrays: infinite loop [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 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) {

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