This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 2 years ago.
Sorry for the strange title, it woudn't let me post the question otherwise. Essentially, I would like to update the count of a variable that is chosen depending on the function input. Here is a simplified version. In my code I have around 30 count variables. The countOne function input would be either 1,2 or 3 and would thus update the relevant count1,count2, or count3 depending on the input.
let count1 = 0;
let count2 = 0;
let count3= 0;
function countNumber(countOne, sum) {
count[countOne] = count[countOne] + sum;
}
The trick is to access property by name. But you need to put your count inside an object.
let data = {
count1: 0,
count2: 0,
count3: 0
};
function countNumber(countOne, sum) {
data["count" + countOne] += sum;
alert(`count1 = ${data.count1} --- count2 = ${data.count2} --- count3 = ${data.count3}`);
}
countNumber(1, 20);
countNumber(1, 5);
countNumber(2, 10);
Related
So, I'm learning Javascript through a book and it has some exercises. One of the exercises asks for you to build two functions, one that creates an array from two numbers provided in the arguments, and the other function has to sum all the numbers in the array. Here's my code:
let beg = 1;
let end = 3;
array = [];
sumNum = 0;
function range(begg, endd) {
for (let count = begg; count <= endd; count++) {
array.push(count);
}
return array;
}
console.log(range(beg, end));
function sum(arrayy) {
for (let i = 0; i <= arrayy.length - 1; i++) {
sumNum = arrayy[i] + sumNum;
console.log(sumNum);
}
console.log("\n")
console.log(arrayy.length - 1);
return sumNum / 2;
}
console.log(sum(range(beg, end)));
array2 = [1, 2, 3];
console.log("\n");
console.log(array2.length);
As I was solving the exercise I kept getting double the sum of all the numbers in the array. I started to print some information and discovered that my arrayy.length is returning double the value it's supposed to return and the loop runs double the times it should run.
Here's my output:
[ 1, 2, 3 ]
1
3
6
7
9
12
5
6
3
Sorry it this is a noob question, but my curiosity is killing me and I have not found anything on the internet, so why am I getting this result?
Thanks in advance.
As Ivan said: The "array" variable is global, so each time you call the range function you keep appending items to that shared array. You should add the array inside your function and return it. Other than that you did a pretty nice job!
function range(begg, endd) {
let array = []
for (let count = begg; count <= endd; count++) {
array.push(count);
}
return array;
}
Also: The sum function should have the "sumnum" variable inside the function to prevent it from increasing every time you call the function:
function sum(arrayy) {
let sumnum = 0;
for (let i = 0; i <= arrayy.length - 1; i++) {
sumNum = arrayy[i] + sumNum;
console.log(sumNum);
}
console.log("\n");
console.log(arrayy.length - 1);
return sumNum / 2;
}
remove the array and sumnum variables from the top of your code to get rid of the global variables.
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 1 year ago.
Improve this question
Im trying to change the X number in the for loop based on what array this function is using. The function gets x random values from an array which he then checks if it isnt the same value and if it isnt the same value he then returns the 2 random values in the array. i tried doing a switch statement like this:
switch(this) {
case array1:
x = 2;
break;
case array2:
x = 3;
break;
}
code
Array.prototype.random = function () {
let result = [];
let bool = false;
let x = 0;
for (var i = 0; i < x; i++) {
result.push(this[Math.floor(Math.random() * this.length)]);
}
while (bool == false) {
if (result[0] === result[1]) {
result.pop();
result.push(this[Math.floor(Math.random() * this.length)]);
} else {
bool = true;
}
}
return result[0] + " + " + result[1];
}
Getting the amount of unique items in the array looks something like
function getUniqueCount(list){
let storage={}, count=0;
for(let i=0; i<list.length; i++){
if(!storage[list[i]]){
storage[list[i]]=true; count++;
}
}
return count;
}
But I'm not sure if that number would help you because you're not saying what you want your function to do
I'm not sure what the x variable is supposed to be. If you just want to return 2 random elements from the array, there's no need for that variable or the result array. Just use two variables.
Array.prototype.random = function() {
let item1 = this[Math.floor(Math.random() * this.length)];
while (true) {
let item2 = this[Math.floor(Math.random() * this.length)];
if (item2 != item1) {
return item1 + " + " + item2;
}
}
}
console.log([1, 2, 3, 4, 5, 6, 7, 8].random());
Remove "()this" because this is a syntax error.
You're trying to do a math calculation:
Math.random() * this.length
Not a syntax error:
Math.random()this.length
And also, you're for loop is not doing anything, because i counts up to x only if i is lower than x. But i and x are both 0, so it will not do anything. If you're trying to make the for loop go up 1 time, just use "2", for 2 results instead of "0".
Next, result.pop() is just returning the value of "result" popped.
Remove that.
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 5 years ago.
I have a function that gets values using for loops and puts them into 1 variable. This variable is them stuck in a form where its is then submitted. But the problem is that the for loop would finish looping by the time the value is entered and submitted. So everytime I test it, the variable "value" = 9999. Can anyone please tell me how to add 1 to variable every time the function loops? Thanks in advance.
function myFunction() {
var value1;
var value2;
var value3;
var value4;
var value;
for (value1 = 0; value1 < 10; value1++) {
for (value2 = 0; value2 < 10; value2++) {
for (value3 = 0; value3 < 10; value3++) {
for (value4 = 0; value4 < 10; value4++) {
value = value1.toString() + value2.toString() + value3.toString() + value4.toString() + '#2018';
document.getElementById('pswd').value = value;
document.getElementById('uid').value = 'test';
document.getElementById('commentForm').submit();
}
}
}
}
}
var loop = setInterval(function() {
myFunction();
}, 2000);
If I'm reading your question correctly, you would like the number to go up by one each time the interval callback is called? You can accomplish this by keeping track of the value outside the function, and do a single increment each time the callback is called. However, you are using 4 variables to basically count from 0 to 9999. You can simplify that a lot by using one variable to increment. Then you can left pad it with zeroes. That would look like this.
var value = 0;
function myFunction() {
var pswd = value.toString().padStart(4, 0) + '#2018';
document.getElementById('pswd').value = pswd;
document.getElementById('uid').value = 'test';
document.getElementById('commentForm').submit();
value++;
if(value > 9999) {
value = 0;
}
}
var loop = setInterval(myFunction, 2000);
If you can't use padStart, you can use slice instead. You can replace that line with the following.
var pswd = ('0000' + value).slice(-4) + '#2018';
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 5 years ago.
I'm trying to create a sort of a bingo number generator, where I generate a unique number and display it alone.
I also want that number + all the next numbers I'm generating to display at the bottom in a line.
My issue here is that whenever it hits a duplicate it loops until it finds a unique number, but displays that number as many times as it looped in the bottom row. So if I generate the numbers [4, 6, 2] and then another 4 it would keep looping until it found another number that's not already in the array.
If it hits the numbers in the array 2 times then found a 5, it would display as [4, 6, 2, 5, 5, 5,]. Is there anything I can do to not make it display the first 2 5's?
window.onload = startup;
function startup() {
document.getElementById("button").onclick = newNumber1;
}
var number = 0;
var bingoNumber = [];
var i;
function newNumber1() {
number = Math.floor((Math.random() * 9) + 1);
clickME();
}
function clickME() {
for (i = 0; i < bingoNumber.length; i++) {
if (number === bingoNumber[i]) {
newNumber1();
}
}
bingoNumber.splice(0, 0, number);
document.getElementById("display").innerHTML = bingoNumber[0];
document.getElementById("row").innerHTML = bingoNumber;
}
<button type="button" id="button">Click</button>
<div id="display"></div>
<div id="row"></div>
Your clickMe calls newNumber1 before it finishes executing, which isn't the problem. The problem is that newNumber1 calls another instance of clickMe, and the loop continues. So by the time newNumber1 generates a unique number, the current and previous instances of clickMe finishes inserting the same new number every time.
Another problem is that, even if you get this working, the loop in clickMe will go on and on if bingoNumber contains all possible unique number that newNumber1 can generate.
Try this:
window.onload = startup;
var bingoNumber = []; // contains all generated numbers
function startup(){
document.getElementById("button").onclick = clickMe;
}
function newNumber(){
// generate a new number
return Math.floor((Math.random() * 9) + 1);
}
function clickMe(){
// if bingoNumber contains all possible values, don't run the rest
// change this to however you want to terminate it
if(bingoNumber.length==9){ return false; }
var num; // number to add to the array
// generate a new number until it is unique
for(num=newNumber();bingoNumber.indexOf(num)>=0;num=newNumber());
// add the unique number in the beginning of the array
bingoNumber.unshift(num);
// display last generated value
document.getElementById("display").innerHTML = bingoNumber[0];
// display all generated value
document.getElementById("row").innerHTML = bingoNumber;
}
Don't add the number to array and display stuff until you really found the unique number:
var found;
function clickME() {
found = true;
for (i=0; i < bingoNumber.length; i++) {
if (number === bingoNumber[i]){
newNumber1();
found = false;
}
}
if(found) {
bingoNumber.splice(0, 0, number);
document.getElementById("display").innerHTML = bingoNumber[0];
document.getElementById("row").innerHTML = bingoNumber;
}
}
This will give you all the numbers without running out of stack space. There is an alert at the end to let you know that all the numbers have been called and will also hide the button so you can't click it again. That one you don't need...but why not?
window.onload = startup;
var bingoNumber = [];
function startup(){
document.getElementById("button").onclick = newNumber1;
}
function newNumber1() {
clickME(Math.floor((Math.random() * 9) + 1));
}
function clickME(num) {
if(bingoNumber.length < 9){
if (bingoNumber.indexOf(num) !== -1){
newNumber1();
}else{
bingoNumber.splice(0, 0, num);
document.getElementById("display").innerHTML = bingoNumber[0];
document.getElementById("row").innerHTML = bingoNumber;
}
}else{
alert("All numbers have been picked");
document.getElementById("button").style.visibility = "hidden";
}
}
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
What is the different between following two methods of defining js function. I have seen this is some code some one given, but could not able to call the function inside of it.
1)
function sum () {
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};
2)
var sum = function () {
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};
The difference is that the var one is defined after the var is created, whereas the static one is defined without waiting for a var to get referenced.
You can call the "var one" only after you declare it since it is "known" at run-time.
example:
a(); // error - doesn't know a
var a = function(){alert('a')}
b(); // ok
function b(){ alert('b')}
First can be used before declaring but second can be used only after its declaration..