Would like javascript loop [closed] - javascript

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 8 years ago.
Improve this question
I am adding subrows below a main row in an html table depending on which main row button is pushed. Here is some of the code:
if (document.getElementById("hdnSub0")) {
roz0 = document.getElementById("hdnSub0").value || 0;
}
...
if (document.getElementById("hdnSub10")) {
roz10 = document.getElementById("hdnSub10").value || 0;
}
nroz0 = parseInt(roz0, 10);
...
nroz10 = parseInt(roz10, 10);
if (intMainRow == 0) {
i = nroz0 + 2
};
...
if (intMainRow == 10) {
i = nroz0 + 2 + nroz1 + 1 + nroz2 + 1 + nroz3 + 1 + nroz4 + 1 + nroz5 + 1 + nroz6 + 1 + nroz7 + 1 + nroz8 + 1 + nroz9 + 1 + nroz10 + 1
};
row = table.insertRow(i);
I would like to write a loop especially for the if(intMainRow...) but I just haven't been able to it figure out.

So use a loop!
Consider getElementById("hdbSub" + i), where i is the loop variable incremented from 0..10. You can then use the loop (or an intermediate array) to go 0..x depending on the value of intMainRow.
For example:
// Because nroz0 + 2, but nrozOther + 1
// (You could also encode with an if/condition in the loop, but I
// feel like showing it this way.)
var incrs = [2,1,1,1,1,1,1,1,1,1,1];
// Running total (I use i/j/k only for loops.)
var total = 0;
// Will loop [0, intMainRow], an inclusive range, because of "<=".
// We loop once for each "field" and add the result in total.
for (var i = 0; i <= intMainRow; i++) {
var elm = document.getElementById("hdnSub" + i);
if (elm) {
// Add the value to the total along with
// the increment (+2/+1) for this index.
// (Each loop "adds" the next value to the equation
// written manually in the the original code.)
var v = parseInt(elm.value, 10) || 0;
total += v + incrs[i];
}
}
row = table.insertRow(total);

Related

The following javascript code gives output 6 . How the code is executed? [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 last year.
Improve this question
Why the output of the following code is not (1,2,3,4,5)?
var x = 0;
while (x < 6) {
x++;
}
document.write(x);
That is because you are only writing to the document once.
For this, you should probably use a for loop.
for (let x = 0+1; x < 5+1; x++) {
document.write(x);
}
This says x = 0 + 1 = 1 (so it starts at 0), then for every x > 5 + 1 (the +1 is so it ends at 5) do this, then add 1 to x.
Simply: x = 1, then when x is over 5, it will write to the document, then it will add 1 to x to continue the loop.
Each time the loop is repeated, the value in the x variable is updated.
x++ increases the value of x by one unit
And you write the final value
This example shows how to achieve this:
var x = 0;
let myArray = [];
while(x<6) {
++x; // We want x to start at 1
myArray.push(x) // Add the new value of x into the array
}
const string = '(' + myArray.join(',') + ')'; // Format the output string by joining the array in a csv format and wrapping with brackets.
document.write(string);

iterate, split, jump between numbers jquery [duplicate]

This question already has answers here:
Access every other item in an array - JavaScript
(4 answers)
Closed 5 years ago.
Im not sure how to ask this question, thats why I didnt found the answer yet... Im trying to iterate a chain number. I mean I created a for loop and instead for showing "30, 60, 90, 120..." I want to jump from 30 to 90 and from 90 to 180. I tried to split the chain but im not doing it right. This is my code:
writeIRFField: function (name, targetElement) {
var $target = $(targetElement).split('1'),
value, values = this.get(name) || [];
$target.html('');
for(var i = 0; i < 4; i++) {
value = values[i] || 0;
$target.append('<label>' + ((i + 1) * 30) + ' ' + translator.getTranslation('days') + ' <input type="number" name="'+ name + '" value="' + value + '" min="0" step="0.01"></label>');
}
},
Where should I split or make the "JUMP" between first value in the array and the third and so on...? (More easy to understand I guess would be like "I have this chain numer: 1, 2, 3, 4, 5..." but I want to output: 1, 3, 5, 7..."
If you want jump on only odd elements (indexes) like 1,3,5,...
You can do it in iteration:
instead of "for(var i = 0; i < 4; i++) {..." ,where i = 0,1,2,3
you can do like "for(var i = 0; i < 4; i+=2) {...", so i=0,2
Another possibility is to iterate over whole list, bit skip even numbers, numbers that divides by 2, like
for(var i = 0; i < 4; i++) {
if(i % 2 == 0)
{
continue;//skip even undexes
}
value = values[i] || 0;
$target.append('<label>' + ((i + 1) * 30) + ' ' + translator.getTranslation('days') + ' <input type="number" name="'+ name + '" value="' + value + '" min="0" step="0.01"></label>');
}

JS Replace multiple phrases [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to replace all %25 with % in puidInp, but only around words that mentioned in newPuidsValues.
I'm trying to solve it with loop, but it changes only one word at one time:
var newPuidsValues = ["banner.tracking_url", "banner.userN", "banner.alt"];
var puidInp = "tyhtyh%25banner.tracking_url%25tyhtyh%25banner.userN%25tyhtyh%25banner.userN%25tyhtyh%25banner.alt%25tyhtyh";
for (var h = 0; h < newPuidsValues.length; h++) {
const reg = new RegExp("\\D{1}\\d{2}" + newPuidsValues[h] + "\\D{1}\\d{2}", "g");
console.log(reg);
var puidOut = puidInp.replace(reg, "%" + newPuidsValues[h] + "%");
console.log(puidOut);
}
Make these small changes to your code:
Declare puidOut outside of your for-loop
Set the initial value of puidOut to puidInp
In the for-loop, use %25 in the RegExp you are creating to capture only the values you need to
In the for-loop, update puidOut in each iteration
Print when done
var newPuidsValues = ["banner.tracking_url", "banner.userN", "banner.alt"];
var puidInp = "tyhtyh%25banner.tracking_url%25tyhtyh%25banner.userN%25tyhtyh%25banner.userN%25tyhtyh%25banner.alt%25tyhtyh";
var puidOut = puidInp;
for (var h = 0; h < newPuidsValues.length; h++) {
const reg = new RegExp("%25" + newPuidsValues[h] + "%25", "g");
console.log(reg);
puidOut = puidOut.replace(reg, "%" + newPuidsValues[h] + "%");
}
console.log(puidOut);

let vs var performance [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been reading about ES6 Let keyword vs existing var keyword.
I've got few questions. I understand that "scoping" is the only difference between let and var but what does it mean for the big picture?
function allyIlliterate() {
//tuce is *not* visible out here
for( let tuce = 0; tuce < 5; tuce++ ) {
//tuce is only visible in here (and in the for() parentheses)
};
//tuce is *not* visible out here
};
function byE40() {
//nish *is* visible out here
for( var nish = 0; nish < 5; nish++ ) {
//nish is visible to the whole function
};
//nish *is* visible out here
};
Now my questions:
Does let posses any memory(/performance) advantage over var?
Other than browser support, what are the reasons why i should be using let over var?
Is it safe to start using let now over var in my code workflow?
Thanks,
R
let is much slower than var in node.js. Version v6.3.0 anyway. Sometimes this is dramatic. The code below is about three times slower if you replace var with let:
function collatz() {
var maxsteps = 0;
var maxval = 0;
var x = 1;
var n;
var steps;
while (x < 1000000) {
steps = 0;
n = x;
while (n > 1) {
if (n & 1)
n = 3*n + 1;
else
n = n / 2;
steps += 1;
}
if (steps > maxsteps) {
maxsteps = steps;
maxval = x;
}
x += 1;
}
console.log(maxval + ' - ' + maxsteps + ' steps');
}
collatz();

How to convert a string into a series of digits in Javascript? [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 8 years ago.
Improve this question
What would be a good way to turn a string into a series of digits in Javascript (I'm not talking about converting "0.5" into 0.5, but more "Hello" into 47392048)?
Any idea appreciated.
Thanks!
You can use the ASCII value of each letter:
"a letter".charCodeAt(0);
Ok, so given your comments, here is a (not widely tested) solution.
var str = "κόσμε 这是一条狗 é €";
$('#orig').after('<dd>' + str + '</dd>');
var result = "";
for (var i = 0, len = str.length, code, paddedCode; i < len; ++i) {
code = str[i].charCodeAt(0).toString();
paddedCode = code.length >= 8
? code
: new Array(8 - code.length + 1).join(0) + code; result += paddedCode;
result += paddedCode;
}
$('#nums').after('<dd>' + result + '</dd>');
var segments = result.match(/.{8}/g);
$.each(segments, function(k, v) {
$('#nums-segmented').after('<dd>' + v + '</dd>');
});
revertedString = '';
for (var i = 0, len = segments.length; i < len; i=i+2) {
revertedString += String.fromCharCode((segments[i] | 0));
}
$('#string').after('<dd>' + revertedString + '</dd>');
Run it at JSFiddle
The trick is to pad number and work with them as string when needed.

Categories

Resources