Index does not exist JavaScript? - javascript

integrityCheck = function () {
var check = ['098f6bcd', '4621d373', 'cade4e83', '2627b4f6'];
for (var i = 0; i <= check.length; i++) {
checkIntegrityOfData(
i,
check[i]
);
}
}
There is probably a very obvious error in my part of the code but im new at JavaScript so i cant really see it.

Array index starts from 0, meaning if an array has 5 elements, the length would be 5 but the max index would be 4.
With your condition logic
You will need to fix your condition logic i <= check.length, last iteration of the loop will try to access check[4] but the last element in check will be in check[3].
Change your loop condition code to
for (var i = 0; i < check.length; i++) {

The problem is your loop goes up to and including the length of the array, however array length starts from 1 whereas array indexes start from 0. Change it to this:
for (var i = 0; i < check.length; i++) {
And it will work. (All I did was change the i<=check.length to i<check.length so it won't iterate over the last index, which is the thing making the error.

Related

Infinite Loop for finding a power set for a string

I'm working on a problem where I need to find all the power set of a given string which are all the possible subsets. I feel like I'm close with my current code but I can't figure out why I'm getting stuck on an infinite loop for my second iteration. I ran it through the debugger but I still can't seem to figure it out even though I'm sure it's very simple. When i = 0 then it goes to the second loop where j = 0 && j < 1 so for example if help is my given str argument then I would expect it to add j + '' and push it into my allSubsets array. The problem is that the j iteration will keep looping and doing j++ and will never stop. I'm not sure why this is. One particular question even if I solve this infinite loop - do I need to update the allSubsets.length in the iteration to keep it updated with the pushed in strings?
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
debugger;
for (let j = 0; j < allSubsets.length; j++) {
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
}
}
return allSubsets;
};
var sortLetters = (word => {
//convert string to an array
//use the sort to sort by letter
//convert array back to string and return
return word.split('').sort().join('');
})
Everytime you push to allSubSets, the length increases, and thus, your loop never ends. A declarative loop runs on the range of the initial loop. See below for a fix based on your code:
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
allSubsets.forEach( (_char, j) => { // declarative loop here
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
})
}
return allSubsets;
};
var sortLetters = (word => {
return word.split('').sort().join('');
})
From MDN web docs:
The range of elements processed by forEach() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach() begins will not be visited by callback. If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (See this example, below.)
See the fourth paragraph under descriptions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

looping through html and deleting not found

So, i'm looping through the document body searching for all "#result>tbody>tr" objects. I'm then trying to search within those elements to see if any of the names exist, if they do, I would like to delete them. I got it working if I don't loop through the names and use a single object. If I try and loop through the names, it only loops four times and then nothing else happens.
Any ideas?
Edit: Currently there are 30 objects the first loop loops through. When I add the second loop into the mix to see if the sub-objects exist, it will only loop through four and than break the loop. Hope that explains better.
Example: https://jsfiddle.net/8c9p7bp5/1/
var dlList = document.querySelectorAll("#result>tbody>tr");
for (var i = 0, len = dlList.length; i < len; i++) {
var names = ['Test', 'Router', 'IP', 'Mod'];
for (var j = 0, len = names.length; j < len; j++) {
var vi = dlList[i].querySelector("td>br>img[title^='" + names[i] + "']");
if(!dlList[i].contains(vi)) {
//dlList[i].remove();
console.log(dlList[i]);
}
}
}
First mistake of your code that you are using same limit for you nested loop "len", in the first iteration the value becomes 4 that's why it will break the parent loop.
You initialize j but never use it in the inner loop.
Try this instead:
var vi = dlList[i].querySelector("td>br>img[title^='" + names[j] + "']");
Also, you should use a different variable than len for the inner loop to avoid running into variable scope issues.

How to get loop value outside the loop

How to get the loop values outside the loop below example only prints the last value, For example if i wanted to print the loop results.
var result;
for (var i=0; i < 10; i++) {
result = i;
}
console.log(result);
Now how can i get the iterated values of the loop which are (1 to 10) in the console, because now i will only print the last value which is 10.
Put the log statement inside the loop where you set the value.
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result);
}
If you only want one output statement, you can concatenate your results before logging:
var result = "";
for (var i=0; i < 10; i++) {
result += i + " ";
}
console.log(result);
This will output 0 1 2 3 4 5 6 7 8 9 10
If you really want to log outside of the loop, wich is quite unnecessary in my opinion, may use an array? :
var result=[];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(...result);
http://jsbin.com/gogeluhavi/edit?console
If you want result make to log magically, you may uses setters and a Proxy, so called Observables.
Enter result=10 into this console, ive implemented a Observable for you: http://jsbin.com/xacujabuwo/edit?console ; You could also paste your for loop...
The Above answears are correct but I would like to clear it up for you so you understand it too.
In your original code you have declared the variable "result" outside the loop, then at each iteration a value is assigned to your variable. So that first time around "result" = 0 , second loop and the "result" = 1 and so on.
When the the for loop is finished it reads the next line which is your console.log() statment with the variable "result". The last time the variable "result" was modified was inside the for loop at the 10th iteration and thats where you let it equal to the iterator,therefore the value of iterator is 11.
In order to display something at every iteration, the console.log() must be placed inside the loop. Check below example
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result); // prints at every iteration
}
Since you didnt add jQuery tag I used only javascript.
Add a input hidden tag
<input id="idOfInput" style="visibility:hidden" type="text">
Set the desired value to the input
for (var i=0; i < 10; i++) {
result = i;
document.getElementById('idOfInput').value = result;
document.getElementById('idOfInput').change(); //note change() is to trigger the event
}
Add change event listener and get the value set in loop
var input = document.getElementById('idOfInput');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value); //you get the value here
});
hope it helps
var result=[];
for (var i=0; i <= 10; i++) {
result.push(i);
}
console.log("Result =>", result);

Javascript stuck at "for" loop

i am newbie learner and i am learning basic javaScript from codecademy.I stuck at "Search Text for Your Name" tutorial 5/7.
here is my question:
your loop should stop when it hits the value of the first iterator (say, i)
plus the length of your myName variable.
here is some informations from to tutorial:
Your second "for" loop
Okay! Last loopy step: add another for loop, this time inside the body of your if statement (between the if's {}s).
This loop will make sure each character of your name gets pushed to the final array. The if statement says: "If we find the first letter of the name, start the second for loop!" This loop says: "I'm going to add characters to the array until I hit the length of the user's name." So if your name is 11 letters long, your loop should add 11 characters to hits if it ever sees the first letter of myName in text.
For your second for loop, keep the following in mind:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
> for(var i = 0; // rest of loop setup
your second should be something like
> for(var j = i; // rest of loop setup Second
think hard about when your loop should stop.
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
and here is my code:
multistr:true
var text = "Hey, how are you \
doing? My name is Emily.";
var myName = "Emily";
var hits = [];
for (var i = 0; i > text.length; i++)
{
if (text[i] === 'E')
{
for(var j = i; j > text.length; j++){
};
};
};
ps: i don't want to pass this tutorial without understand it. please help me. teach me.
for (var i = 0; i > text.length; i++) should be
for (var i = 0; i < text.length; i++)
otherwise it won't ever meet the criteria to even start the loop.
Welcome on board! You confused > with <. Your loops won't run because for the first check when i = 0 it certainly does not hold that 0 > text.length, because text.length is at least 0 (there are no strings shorter than the empty string).
You should make a habit of manually going through your loops for the first two steps and then check what happens just before the loop ends.
Here is what I got for my code:
for ( i = 0; i < text.length; i++)
{
if ( text[i] === "E")
{
for( var j = i; j < (myName.length + i ); j++)
{
hits.push(text[j]);
}
}
};
It looks like you were missing the " + i " part in your second for loop. That seems to make sure that the first loop will be included. I tried it without the "+ i" and it does not work.
I tried continuing directly from the second for loop using a "+ j" and that only crashes the browser.

Javascript array splice in animation

I'm currently working on a map generator in canvas.
Here is the code working code : http://jsfiddle.net/RtPmm/
and the piece that raise an issue :
MapBuilder = function(){
...
this.checkPath = function(){
...
(logic condition ...) {
var i = Game.builders.indexOf(this);
Game.builders.splice(i,1); /!\
}
and in the render function :
for (var i = 0, len = Game.builders.length; i < len; i++) {
Game.builders[i].checkPath();
}
My problem is that when my MapBuilder objects are supposed to be remove from the array, the animateloop function still find deleted index when it iterate throughGame.builders array.
I can't really find this out..
Thanks for taking the time to leave an answer (or comment)
Well, it's because you are looping until the initial length of the array is reached, but the length changes as you remove items and the items gets shifted.
There are several solutions to this problem, like looping backward instead, or something like:
var builders = Game.builders,
builder;
for (var i = 0, len = builders.length; i < len; i++) {
(builder = builders[i]).checkPath();
if (builders[i] !== builder) {
//builder was removed, fix the loop
--i; --len;
}
}

Categories