Create variables dynamically with a For Loop Javascript - javascript

The title plus the following example are self-explanatory of what I don't achieve :-)
The idea is to replace something + counter in order to make it work.
for (var counter = 1; counter <= 6; counter++) {
var something + counter = $('element' + counter);
(something + counter).removeAttribute('class');
}

You could create an array, but much more simply:
for (var counter = 1; counter <= 6; counter++) {
$('element' + counter).removeAttribute('class');
}

Just do:
for (var counter = 1; counter <= 6; counter++) {
$('element' + counter).removeAttribute('class');
}
Unless you wanted to store it outside of the loop, in which case use an array.

Use an array.
var something = [];
for (var counter = 1; counter <= 6; counter++) {
something[counter] = $('element' + counter);
something[counter].removeAttribute('class');
}

Why can't you just get rid of the var altogether??
for (var counter = 1; counter <= 6; counter++) {
$('element' + counter).removeAttribute('class');
}

for (var counter = 1; counter <= 6; counter++) {
window[something + counter] = $('element' + counter);
window[something + counter].removeAttribute('class');
}
after that there will be a set of fields in window object, named something1, something2 etc (if something == "something", of course)

Related

JavaScript eval() not working with variable name

why eval() is not executing my code?
for (var i = 1; i <= 3; i++) {
str = "var foo_" + i + "_bar = " + i;
eval(str);
}
console.log(foo_1_bar);
console.log(foo_2_bar);
console.log(foo_3_bar);
The variable foo_2_bar is not declared at that iteration (i = 1). You need to put the console.log(...) outside of the loop.
I assume you're playing with js because eval is a little dangerous.
for (var i = 1; i <= 3; i++) {
str = "var foo_" + i + "_bar = " + i;
eval(str);
}
console.log(foo_1_bar);
console.log(foo_2_bar);
console.log(foo_3_bar);
Your logged variable doesn't exist
for (var i = 1; i <= 3; i++) {
str = "var foo_"+ i +"_bar = " + i;
eval(str);
console.log(foo_1_bar);
}

break statement remove only second loop

i am using javascript nested loops and i need to break second loop on some condition but only second loop not the first one can anybody tell me how is it possible
my code
var myVar = "";
var i, j;
loopone:
for (i = 0; i < 3; i++) {
text += "<br>" + "i = " + i + ", j = ";
looptwo:
for (j = 10; j < 15; j++) {
if (j === 12) {
break;
}
document.getElementById("demo").innerHTML = text += j + " ";
}
}
not this break statement stop both loops but i want to stop only second loop.
Any help would be appriciated. thanks in advance!
Well its so simple of you are using loops with label then you just have to mention the label(loop name) after break statement like this
var myVar = "";
var i, j;
loopone:
for (i = 0; i < 3; i++) {
text += "<br>" + "i = " + i + ", j = ";
looptwo:
for (j = 10; j < 15; j++) {
if (j === 12) {
break looptwo;
}
document.getElementById("demo").innerHTML = text += j + " ";
}
}
this will break only loop with name looptwo

Increment and Repeat number 3 times in a incremental loop in Java Script

So the goal is to have the following:
k_1_1
k_1_2
k_1_3
k_2_4
k_2_5
k_2_6
k_3_7
and so on
What I have so far is:
But I think I'm way off....
while (var qi = 0; qi <= 9; qi++ ) {
for(var ai = 0; ai <= 3; ai++ ) {
var thisName = "k_" + ai + "_" + qi;
var thisValue = "";
localStorage.setItem(thisName, thisValue);
}
}
Any help would be apreciated.
thanks
No need for two loops if you use a little ingenuity:
for (var i = 0; i <= 9; i++) {
var thisName = "k_" + (Math.floor(i/3)+1) + "_" + (i+1);
var thisValue = "";
localStorage.setItem(thisName, thisValue);
}
You're using a While loop with For loop arguments. While loops keep looping while a condition is TRUE. Why not switch it to a For loop like so (also, your qi and ai are switched):
for(var qi = 1; qi <= 9; qi++ ) {
for(var ai = 1; ai <= 3; ai++ ) {
var thisName = "k_" + qi + "_" + ai;
var thisValue = "";
localStorage.setItem(thisName, thisValue);
}
}
An alternate solution:
for (var ai = 1; ai <= (27) ; ai++ ) { // 27 was picked arbitrarily (3 * 9)
// set to what ever upper limit you need
// the ceiling of the current ai number divided by 3 will give you your qi
var qi = Math.ceil((ai/3));
//setting your values
var thisName = "k_" + qi + "_" + ai;
var thisValue = "";
//reporting
console.log(thisName, thisValue);
}

Javascript Loto Game

How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();

Javascript: getting rid of nested loop

It's been a while since I wrote any Javascript. Is there a more elegant way to do this. Specifically want to get rid of the second loop:
<script>
var number = 0;
for (var i=1; i<11; i++) {
for (var x=1; x<11; x++) {
if (i==1) {
number = x;
} else {
number = Math.pow(i, x);
}
document.write(number + " ");
if (x == 10) {
document.write("<br>");
}
}
}
</script>
I would stick with 2 loops but i would change one if statement and move it after the 2nd loop and avoid document.write and insert it all at once to reduce the number of time you change the DOM
let result = ''
for (let i = 1; i < 11; i++) {
for (let x = 1; x < 11; x++)
result += (i==1 ? x : Math.pow(i, x)) + ' '
result += '<br>'
}
document.body.insertAdjacentHTML('beforeend', result)
Edit If you really don't want the 2nd loop:
let result = ''
// you must swap the condition to check for x instead of i
for (let i = 1, x = 1; x < 11; i++) {
result += (x==1 ? i : Math.pow(x, i)) + ' '
// and reset i and increase x yourself
if (i == 10) {
i = 0
x++
result += '<br>'
}
}
document.body.insertAdjacentHTML('beforeend', result)
Edit2 just for the fun: No for loops.
Just a recursive function :P
function build(i = 1, x = 1, res = '') {
res += (x == 1 ? i : Math.pow(x, i)) + ' '
i == 10 ? (x++, i=1, res += '<br>') : i++
return x == 11 ? res : build(i, x, res)
}
document.body.insertAdjacentHTML('beforeend', build())
In terms of 'elegancy', I'd go for for... in loops or map function. That doesn't solve your nested loop though.
On a side note, nested loops are not necessarily bad. If that's the correct way to implement the specific algorithm, then that's how it is.
Using Math.pow() is un-necessary overhead. Nested loops are not necessarily bad.
var number = 0;
for (var i=1; i<11; i++) {
document.write(i + " ");
number = i;
for (var x=2; x<11; x++) {
number = (i == 1) ? x : number * i;
document.write(number + " ");
}
document.write("<br>");
}
Another way of doing it with 1 loop only, tho not as clean:
var number = 0;
var x = 1;
var calc = 0;
var calcx = 1;
var increment = false;
for (var i=1; i<101; i++) {
increment = false;
calc = i % 10;
if(calc == 0){
calc = 10;
increment = true;
}
if (calcx==1) {
number = calc;
} else {
number = Math.pow(calcx, calc);
console.log(calcx+" "+calc);
}
document.write(number + " ");
if (i % 10 == 0) {
document.write("<br>");
}
if(increment){
calcx++;
}
}
Here's another way with only one loop:
[...Array(100)].map((_,i) => {
document.write(((i>9)?Math.pow(Math.floor((i+10)/10),(i%10)+1):i+1) + ' ' + ((i%10==9)?'<br>':''));
});

Categories

Resources