The second for loop in a function doesn't work - javascript

I have a function like below:
function launching() {
let ranges = document.getElementsByClassName('range');
liczba2 = 0;
console.log(ranges);
let czeks = document.getElementsByClassName('check');
liczba = 0;
eluwina = 0;
for (let i = 0; i <= czeks.length; i++) {
if (czeks[i].checked) {
liczba ++;
console.log(liczba);
}
}
for (let n = 0; ranges.length; n++) {
let val = ranges.getAttribute('value');
console.log(val);
}
}
The first for loop works fine. However the second one:
for (let n = 0; ranges.length; n++) {
let val = ranges.getAttribute('value');
console.log(val);
}
Doesn't work at all. Even if there's just console log after first loop, it won't execute. I'll be grateful if anyone could help me. Thanks in advance :).

The second loop should be:
for (let n = 0; n < ranges.length; n++) {
let val = ranges[n].getAttribute('value');
console.log(val);
}
In your code, if ranges.length == 0, the loop will end immediately, since the condition ranges.length is falsey. Otherwise it will be cause an infinite loop, because the value of ranges.length doesn't change, and a non-zero value is truthy.
However, the loop will stop because ranges.getAttribute('value') will get an error. ranges is a NodeList, not a single element, and it doesn't have a getAttribute() method. You need to index it to get the current element in the iteration.

Related

why my code doesn't work when I am trying to concatenate a function's return value with a string?

So, in this code I have a string of 0's and 1's and the length of the string is 32, which will be split in 6 equal parts but the last part will have the length of 2 so I will add (4) 0's after that which will make its length 6. So I wrote a function that will add the remaining 0's which is padding(num).
And that function will be invoked in side the slicing(str) function.
But the code breaks when I try to do execute.
Any help?
Thanks.
// This code works.
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
let f = padding0s(2);
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
// But this does not..
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
let f = padding0s(res[temp1].length);
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
Always define variables before using them
Not doing so can result in undefined behaviour, which is exactly what is happening in your second case. Here is how:
for (i = 0; i < str.length; ) {...}
// ^ Assignment to undefined variable i
In the above for-loop, by using i before you define it, you are declaring it as a global variable. But so far, so good, as it doesn't matter, if not for this second problem. The real problem is the call to padding0s() in your loop. Let's look at padding0s:
function padding0s(num) {
...
for (i = 0; i < 6 - num; i++) {
s += "0";
}
}
This is another loop using i without defining it. But since i was already defined as a global variable in the parent loop, this loop will be setting its value. So in short, the value of i is always equal to 6 - num in the parent loop. Since your exit condition is i < str.length, with a string of length 32 the loop will run forever.
You can get around this in many ways, one of which you've already posted. The other way would be to use let i or var i instead of i in the parent loop. Even better is to write something like this (but beware that padEnd may not work on old browsers):
function slicing(str) {
return str.match(/.{1,6}/g).map((item) => {
return item.padEnd(6, "0");
});
}
console.log(slicing("01000011010011110100010001000101"));

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well.
cnt = 0;
for (let i = 0; i < this.fin.length; i++) {
for (let j = 0; j < this.fin.length; j++) {
if (this.fin[i] == this.fin[j]) {
cnt++;
if (cnt > 1) {
this.fin[j] = '';
}
}
if (j == this.fin.length - 1) {
cnt = 0;
}
}
}
this.ntmtg1 = true;
count = 0;
for (let j in this.fin) {
if (this.fin[j] == '') {
this.fin.splice(parseInt(j));
}
}
your logic is almost correct. The couple of mistakes you did are:-
In the for loop in the last part of your code, when you use for( let i in SomeCollection) 'i' will be the value and not index in the array. I think you want to access the index and not the value. I think you should use should use traditional for loop like for(int i =0; i<fin.length;i++).
You need to use splice with two arguments to delete some value from the array.
here is the link https://www.w3schools.com/jsref/jsref_splice.asp
You can do that in simply just one line of code with ES6 feature and Set :
var fin = ["Vivek","Vivek","Mak","Nik","Mak","Hir","Hari","Nur","Nik"];
var result = [...new Set(fin)];
console.log("Fin Total :" , fin.length , ", Result Total :" , result.length);
console.log(result);
Couple of fixes to your code
don't use for in if you're going to mutate the array
splice with only one argument splices from the index to the end of the array, so add a second argument, the length of the splice
in the code below, I omit this for simplicity
Also, I moved were cnt is defined, so no if condition gymnastics needed to reset it
const fin = [1,3,6,7,3,2,4,5,6,4,3,2,1,4,5];
for (let i = 0; i < fin.length; i++) {
let cnt = 0;
for (let j = 0; j < fin.length; j++) {
if (fin[i] == fin[j]) {
cnt++;
if (cnt > 1) {
fin[j] = '';
}
}
}
}
let count = 0;
for (let i = 0; i < fin.length; i++) {
if (fin[i] == '') {
fin.splice(i, 1);
--i; // we've removed an item
}
}
console.log(fin);
fin:any = ["OMAD","SVAC","SVCH","SVAD","LGAG","OMAM","OTBK","OTBH","LGAX","LGBL","SVAN","LGAD","SVAB","SKAP","LGRX","SVAA","SVAS","DNAS","EGEI","NCAT","SVBS","SVBL","SVFM","EPKG","OBBB","OBBS","OBKH","LTFD"
,"SVBC","SVBI","SVBM","SVBB","SVBO","TNCB","SVBZ","SKBU","SKBN","SVCI","SVCD","SVCL","SVCN","SVCC","SVCS","SVCO","SVCZ","SKGO","SVCP","NZCG","SVQM","SVCA","LGSA","MWCB","CYCK","SVCB","SVPI","MRCU","EKCN"
,"SVCR","SKCV","SVUR","SVCU","SVRB","TNCF","TNCC","LGTT","VRMD","OMDW","SVLL","SVED","SVRS","SVEM","SVJI","SVVG","LGEL","SVEZ","NZEV","EDTF","SVFT","VRMR","SKGB","SVGU","SVGD","SVGT","SVGI","SVQJ","EKHM"
,"SVQF","LSPK","SVQL"];

Javascript: For loop in a for loop

I'm doing a scoring app as practice, and I'm trying to get an object to calculate the total score for a player. Here is the part I'm struggling with:
totalScore: function () {
"use strict";
debugger;
var sum = 0;
for (var i = 0; i < this.players[i].length; i++) {
for (var n = 0; n < this.players[i].score[n].length; n++) {
sum += this.players[i].score[n];
}
this.players[i].totalScore = sum;
} }
So I have a main object scoreTable. players is an array of objects which includes another array called score. So what I'm trying to do is create a totalScore object function that runs a loop through the players array that loops on each score array and finds the sum of that array.
I don't know why, but when I run through it on the dubugger, it goes into the first for loop, finds the first array of players, then just skips to the end of the function without running the next loop. I'm not sure why it's doing that.
for (var i = 0; i < this.players[i].length; i++) {
for (var n = 0; n < this.players[i].score[n].length; n++)
}
This should be:
for (var i = 0; i < this.players.length; i++) {
for (var n = 0; n < this.players[i].score.length; n++)
}
Try following:
totalScore: function () {
for (var i = 0; i < this.players.length; i++) {
var player = this.players[i];
player.totalScore = 0;
for (var n = 0; n < player.score.length; n++) {
player.totalScore += player.score[n];
}
}
}
This fixes not only syntax errors, but also the sum-logic itself: sum variable from initial post won't reset for each new player in the top-level loop.

setting a variable to each element of an array

i have function:
function getFieldNames(arrayOfRecords) {
var theStuff;
for (var i = 0; i = arrayOfRecords.length - 1; i++){
theStuff = arrayOfRecords[i];
theList = theStuff.split('" ');
for (var j = 0; j = theList.length - 1; j++) {
var v = theList[j].split('="');
fName1[i][j] = v[0];
}
}
return fName1;
}
the argument arrayOfRecords is an array, and i dont know how to setup to the 'theStuff' variable an array element? When I do like it is above, i get something stupid.
can anyone help me? :)
There may be other problems but the one that leaps out at me is your for loop header:
for (var i = 0; i = arrayOfRecords.length - 1; i++)
The second part should be a condition, which when evaluated to false will stop the loop from running. What you probably wanted was:
for (var i = 0; i < arrayOfRecords.length; i++)
So when i is not less than arrayOfRecords.length, the loop will stop. Alternatively (to keep the - 1, but I tend to use the above version):
for (var i = 0; i <= arrayOfRecords.length - 1; i++)
The same goes for the nested loop.

Javascript: confused about how nested for loops work

Why do nested for loops work in the way that they do in the following example:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
var newTimes = [];
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
In this example I would have thought console.log would give me the following output:
["04/11/10"]
["86kg"]
["05/12/11"]
["90kg"]
["06/12/11"]
["89kg"]
However, I actually get this:
["04/11/10"]
["04/11/10", "86kg"]
["05/12/11"]
["05/12/11", "90kg"]
["06/12/11"]
["06/12/11", "89kg"]
Is anyone able to help me understand this?
EDIT:
Thanks for all your responses!
You are redefining newTimes on every single loop and you are outputting to the console on each column push.
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
}
}
console.log(newTimes);
Returns: ["04/11/10", "86kg", "05/12/11", "90kg", "06/12/11", "89kg"]
http://jsfiddle.net/niklasvh/SuEdt/
// remember that the increment of the counter variable
// is always executed after each run of a loop
for (var i = 0; i < n; i++) {
// some statement(s) to do something..
// initializes child-loop counter in the first run of the parent-loop
// resets child-loop counter in all following runs of the parent-loop
// while i is greater than 0 and lower than n
for (var j = 0; j < p; j++) {
// some statement(s) to do something..
// initializes grandchild-loop counter in the first run of the child-loop
// resets grandchild-loop counter in all following runs of the child-loop
// while j is greater than 0 and lower than p
for (var k = 0; k < q; k++) {
// some statement(s) to do something..
// or add more internal loop-nestings if you like..
}
}
}
// if the counter variables of the descendent-loops were set before the loop-nesting,
// the inner loops would only run once, because the counter would keep the value
// of the abortion condition after the loop is finished
Do this:
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
You are re-initializing newTimes each time through the loop.
You output would be appropriate if the log statement would read
console.log(times[i][x]);
Instead you output your complete new list newTimes which is initialized outside the inner loop and grows with each inner loop iteration.
The problem is in the second round of the inner loop, where it pushes the second element into newTimes. Anyway I don't understand the reason of inner loop. You can write much simpler:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
console.log(time[i][0]);
console.log(time[i][1]);
}

Categories