What's the difference between these two code? - javascript

while(todoList.children[0] !=null){
todoList.children[0].remove();
}
for(let i = 0 ; i<todoList.childElementCount ; i++){
console.log(i);
todoList.children[0].remove();
}
I have a list and it has 5 elements in it. I want to remove elements from it. If i try to reach lists element count it gives 5 value with no problem .When i use while loop it works but for loop just runs 3 times.

A better way would be to store the todoList.childElementCount first in a new variable, and use that variable in the terminating condition of for-loop.
Or if you do not want to store todoList.childElementCount in a new variable, then:
for(let i = todoList.childElementCount-1; i>=0 ; i--){
console.log(i);
todoList.children[0].remove();
}

todoList.children[0] is same as todoList.firstChild
while(todoList.children[0] !=null){
todoList.children[0].remove();
}
looks up if the todolist has ONE child, and if so, then it removes it.
for(let i = 0 ; i<todoList.childElementCount ; i++){
console.log(i);
todoList.children[0].remove();
}
looks up every single time HOW MANY childs there are and then removes the firstchild. So therefore it is not that performant.

It would be the same if code was:
let initialChildCount = todoList.childElementCount;
for(let i = 0 ; i < initialChildCount; i++){
console.log(i);
todoList.children[0].remove();
}
In your code you keep decreasing todoList.childElementCount therefore loop ends faster

Related

for loop to print out multiple arrays with similar names

I've got multiple arrays, like so:
bugNames0 = ["wasp", "roach", "stinkbug", "mantis"];
bugNames1 = ["hornet", "beetle", "ant", "termite"];
bugNames2 = ["gnat", "fly", "grub", "chigger"];
bugNames3 = ["flea", "bed-bug","maggots", "cricket"];
Next up I have this for loop:
function bugLoop() {
for (var i=0; i < 4 ; i++){
console.log(bugNames0[i]);
}
}
That will successfully print the first array to console, or each individually if I manually update the number in the array's name.
But is there a way to do something more like this? This following code bit doesn't work, but I hope it explains what I am trying to do:
for (var i=0, j=0; i < 4; i++) {
console.log(bugNames(i)[j]);
}
}
Here i represents the bugName#, which I would like to get to update through 0 - 3 as the loop runs, printing out only the first option of each array represented by j.
Goal outcome printed to console would be:
"wasp", "hornet", "gnat", "flea"
Or something like that.
If possible I would like solutions only using vanilla JS as I'm working on a project (self assigned exercise) where I'm trying to complete it using vanilla. Kind of a force myself to get the know the language better exercise.
(Also, I've only been coding for 4 months, so sorry if this is a noob question. I couldn't find the answer online anywhere, just lots of loops on printing out arrays normally.)
If you can store your arrays within an array, that would be a better option.
For instance:
bugNames[0] = ["wasp", "roach", "stinkbug", "mantis"];
bugNames[1] = ["hornet", "beetle", "ant", "termite"];
bugNames[2] = ["gnat", "fly", "grub", "chigger"];
bugNames[3] = ["flea", "bed-bug","maggots", "cricket"];
Then you can loop through the bugNames array normally.
You could store all four arrays into one larger array (each bugNames array would simply be an element within this larger array). Let's call it bugCollection:
bugCollection = [["wasp", "roach", "stinkbug", "mantis"], ["hornet", "beetle", "ant", "termite"], ["gnat", "fly", "grub", "chigger"], ["flea", "bed-bug","maggots", "cricket"]]
Alternately, you could keep your variable storage of these arrays and say:
bugCollection = [bugNames0, bugNames1, bugNames2, bugNames3]
Then you could iterate through the larger array, logging out the index at each.
var oneFromEachArray = function(index) {
for (var i = 0; i < bugCollection.length; i++) {
console.log(bugCollection[i][index]);
}
}
oneFromEachArray(0) // Console logs 'wasp', 'hornet', 'gnat', 'flea'
You could try eval
for (var j=0; j < 4 ; j++){
for (var i=0; i < 4 ; i++){
eval("console.log(bugNames" + j + "[i]);");
}
}
You could use the function eval() like this:
for (var i=0, j=0; i < 4; i++) {
console.log(eval('bugNames' + i)[j]);
}
But did you already consider utilizing an array of arrays? Maybe that would be a cleaner way to achieve the same thing.
You can always access your variables using window object. Please use following code to access your variable dynamically.
for (var i=0, j=0; i < 4; i++) {
console.log(window["bugNames"+i][j]);
}

Check if the elements in array have been connected into a pair in Javascript

I have a problem that I can't seem to solve, maybe you can help.
There is an array I have. E.g. ['#dog','#cat','#mouse']
I want to reiterate through each value in that array and connect it to all the other values in that same array (through building a DB query).
However, because I'll be writing that in a database I need to avoid duplicates.
So if the #cat has been already connected to #mouse then by the time my for statement reaches the #mouse i want it to skip adding connection to #cat (and also to #dog because it was already connected on the first iteration to #mouse.
I've been trying with for loops, such as
for (var i=0; i<animals.length; i++) {
for (var j = 0; j<animals.length; j++) {
if (animals[i] !== animals[j]) {
// adds connection between animals[i] and animals[j]
}
}
}
But what's the best way to implement a check of the already existing pairs? (where it doesn't matter which element is the first, which is the second - e.g. my graph is not unidirectional).
This especially becomes a problem if I'm going to have more than 4 elements in the array...
Thank you for your help!
for (var i=0; i<animals.length; i++) {
for (var j = 0; j<i; j++) {
if (animals[i] !== animals[j]) {
// adds connection between animals[i] and animals[j]
}
}
}
This way, each element of the array is only compared against those before it in the array. I think this is much closer to what you want.
In the inner loop, you only want to make connections to elements not yet visited by the outer loop:
for (var i=0; i<animals.length; i++) {
for (var j = i+1; j<animals.length; j++) {
// ^^^
// adds connection between animals[i] and animals[j]
}
}
That way you won't get duplicate edges (assuming that animals itself is duplicate-free)

JavaScript remove all elements with name

I am trying to use JavaScript to remove all the elements with a certian name, but it is only removing the first one.
My code is:
var ele= document.getElementsByName("javascriptaudio");
for(var i=0;i<ele.length;i++)
{
ele[i].parentNode.removeChild(ele[i]);
}
Can anyone tell me what is wrong?
Thanks
I don't have enough rep to comment on Álvaro G. Vicario. The reason that it works is that the element is removed from ele when it is removed from the DOM. Weird.
The following code should work equally well:
var ele= document.getElementsByName("javascriptaudio");
len = ele.length;
parentNode = ele[0].parentNode;
for(var i=0; i<len; i++)
{
parentNode.removeChild(ele[0]);
}
Try removing them backwards:
var ele = document.getElementsByName("javascriptaudio");
for(var i=ele.length-1;i>=0;i--)
{
ele[i].parentNode.removeChild(ele[i]);
}
The problem is that removing elements from ele shifts indexes: if you have 5 items (0 to 4) and remove item 0 you then have 4 items ranging from 0 to 3 (4 becomes 3, 3 becomes 2, etc.); you should then remove item 0 but your i variable has already incremented to 1.
you need to save length of array outside the loop because it is evaluated with each pass if you place it inside loop criteria. That way you will have correct amount of iterations. Furthermore you need to delete first item in loop each time because with each pass you lose 1 item so you will be outside of range at the end of process.
var ele = document.getElementsByName("javascriptaudio");
var elementsCount = ele.length;
for(var i=0;i<ele.length;i++){
ele[0].parentNode.removeChild(ele[0]);
}
Try the following jQuery code:
$("[name=javascriptaudio]").remove();

Array iteration with iself

I have an array of values like:
["34.44","55.22","15.32","21.67","98.76","14.57"]
and I want to iterate between themselves like
Calculate(34.44, 55.22);
Calculate(34.44, 15.32);
Calculate(34.44, 21.67);
Calculate(34.44, 98.76);
Calculate(34.44, 14.57);
Calculate(55.22, 15.32);
Calculate(55.22, 21.67);
Calculate(55.22, 98.76);
and so on...
what would be best way to iterate them in Javascript?
I was easily thinking having two arrays with same values and interate between first array and second array but could exists a better way for performance...
Thanks in advance to everyone!
Cheers,
Luigi
for( var i=0; i<myarray.length; i++ ) {
for( var j=i+1; j<myarray.length; j++ ) {
Calculate( myarray[i], myarray[j] );
}
}
Array.forEach doesn't allow to do this kind of iteration, your best option is to just make two loops on the index:
for (var i=0; i<x.length; i++) {
for (var j=i+1; j<x.length; j++) {
... do whatever you need with x[i], x[j] ...
}
}
if instead you need to process x[a], x[a] pairs (i.e. the same element twice) and also both x[a], x[b] pair and x[b], x[a] pair then forEach can shorten the code (and probably will run faster).
x.forEach(function(x1){ x.forEach(function(x2){
... do whatever you weant with x1, x2 ...
})});
but note that forEach will iterate only over the elements that have been actually assigned, not in all the range 0..length-1. For example after
x = [];
x[2] = 42;
the loop x.forEach(...) will not iterate over the undefined elements x[0] and x[1].
You can use nested forEach methods on the array.
var array = ["34.44", "55.22", "15.32", "21.67", "98.76", "14.57"];
array.forEach(function(numberLeft, indexLeft) {
array.forEach(function(numberRight, indexRight) {
// skip previous numbers and itself
if (indexLeft >= indexRight)
return;
Calculate( numberLeft, numberRight );
});
});

javascript array for loop i+1 returning undefined

array ref.length = 7 (0 - 6), and I want to try to match ref[0]['x'] to ref[1]['x'] I am doing this:
for(var i=0;i<ref.length;i++){
if( ref[i]['x'] != ref[i+1]['x'] && ref[i+1]['x'].length > 0 )
//do something
}
The for loop is iterating all the way to array number 6 then element 6+1 is blank so I get an error on the if statement line saying ref[i+1] is undefined....
is there a better way to do this?
Better:
for (var i=ref.length-2;i>=0;i--)
Javascript will evaluate the condition on each iteration, so it's generally preferable go backwards instead. With this construct "ref.length" is only evaluated once. Another alternative I like which will perform the same:
var i=ref.length-1;
while (i--) {
}
(Normally you'd be i=ref.length-1 in the first example, and i=ref.length in the second, but you're trying to stay one less than the array length).
for (var i=0; i<ref.length-1; i++) { // Note the "-1".
This way when you use the index i+1 you're still in bounds.
for (var i = 0; i < ref.length - 1; i++)
What about:
for(var i=0;i<ref.length-1;i++){
If you just use ref.length-1 won't that solve your problem? I might not fully understand what you're asking.
Here's a simple solution.
Just count the counter again.
if( ref[i]['x'] != ref[++i]['x'] && ref[++i]['x'].length > 0 )

Categories

Resources