How to add a variable in javascript? [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
var count=0 ;
for(var x=0; x<data_len; x++)
{
count = count + num_arr[x];
}
// alert(count);
If count = 352 I want to add 3+5+2 which is 10 and then 1+0 which is 1.

function sumParts(x) {
var sumX = 0;
var strX = x.toString();
var arrX = strX.split("");
for (a = 0; a < arrX.length; a++) {
sumX += parseInt(arrX[a], 10);
};
return sumX;
}
y = sumParts(count);
z = sumParts(y);
// y = 10; (3 + 5 + 2)
// z = 1; (1 + 0)
And, I believe (untested), if the return was changed to return sumParts(sumX), it would continue until it was a single digit integer.

You have an array of strings, not numbers. You can convert them to numbers with:
count = count + +num_arr[x];
The second + is the unary plus operator, and will cast num_arr[x] to a number.
If your numbers are all integers, you can use:
count = count + parseInt(num_arr[x], 10);
or (if you have floats):
count = count + parseFloat(num_arr[x]);

Convert count into a string :
var count = 352;
count += ''; // makes a string : "352"
while (count.length > 1) {
count = Function('return ' + count.split('').join('+') + ';')() + '';
}
This part :
Function('return ' + count.split('').join('+') + ';')
Gives successively :
function () { return 3+5+2; }
function () { return 1+0; }

Related

How to loop randomize javascript function in html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I know this is very simple question, but I don't know why it only giving same output.
I'm trying to randomize 4 numbers from 1 to 100
I'm very new to javascript
this is my code:
function myFunction() {
var text = "",
i;
var x = Math.floor((Math.random() * 100) + 1);
for (i = 1; i <= 4; i++) {
text += " number " + x;
}
document.getElementById("rand").innerHTML = text;
}
<button onclick="myFunction()">Generate</button>
<p id="rand"></p>
You are calling your randomize part of code outside the for loop. It should be recalculated on every step of the loop. Something like this
function myFunction() {
var text = "",
i;
for (i = 1; i <= 4; i++) {
var x = Math.floor((Math.random() * 100) + 1);
text += " number " + x;
}
document.getElementById("rand").innerHTML = text;
}
<button onclick="myFunction()">Generate</button>
<p id="rand"></p>
function myFunction() {
var text = "";
var i = 0;
randNos = [];
while(i<4) {
x = rand();
if(randNos.indexOf(x) === -1) {
text += " number " + x ;
randNos.push(x);
i++
}
}
document.getElementById("rand").innerHTML = text;
}
function rand() {
return Math.floor((Math.random() * 100) + 1);
}
You were trying to print the same random no 4 times. You just need to move your random no line inside the loop

How do I write a function to multiple numbers from 1-10? [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 2 years ago.
Improve this question
var a = 7;
var b;
for (var i = 1; i <= 10 ; i++) {
b = a * i;
document.write(" " +a+ "*", + b + "<br>");
}
This works however it has to be a loop, not code for one specific number so I need to write it so it goes for all numbers 1 through 10.
I'm using http://js.do which we have to use.
You need to have two loops - one nested inside the other - both going from 1 to 10.
Something like:
for (let i = 1; i <= 10; i++) {
for (let j = 1; j <= 10; j++) {
let s = i * j;
document.write(i + "*" + j + "=" + s + "<br>");
}
}
Or, to allow the user to enter a number of their choice:
let a = prompt("Enter a number: ");
if (a) {
for (let i = 1; i <= 10; i++) {
let b = i * a;
document.write(a + "*" + i + "=" + b + "<br>");
}
}
var a;
var b;
for (var a = 1; a <= 10 ; a++) { // loop the a number 1 to 10
for (var i = 1; i <= 10 ; i++) {
b = a * i;
document.write(" " +a+ "*", + b + "<br>");
}
}

Javascript row number using for loop? [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 2 years ago.
Improve this question
Can anyone help me with this Javascript problem? The code I've write is not quite right.
function tes() {
var c = document.getElementById('Text');
var a = document.getElementById('a').value;
var txt = '';
for (i = 1; i <= a; i++) {
for (j = 1; j <= a; j++) {
if (j == i) {
txt += i.toString();
} else {
txt += i.toString();
}
}
txt += '<br/>';
}
c.innerHTML = txt;
}
<input id="a">
<button onclick="tes()">Input</button>
<div id="Text"></div>
Javasript Problem
Expected output:
1 1 1 1 1
1 1 1 2 2
1 1 3 3 3
1 4 4 4 4
5 5 5 5 5
Since your problem required an input, you would be running the code when input is received. The only thing you got incorrect was really the if statement logic. rowAmm is a variable holding for the amount of 1s in a row, if j was less than that, add another 1, otherwise add i which was the row number.
You won't have to do a .toString() function either if you're adding it to a variable which is already declared a string var txt = ''. Just like 5 + "5" will become 55 while 5 + 5 will be 10
var a = document.getElementById("a");
var textBox = document.getElementById("Text");
function makeSquare() {
var b = a.value;
var txt = '';
for (i = 1; i <= b; i++) {
var rowAmm = b - i;
for (j = 1; j <= b; j++) {
if (j <= rowAmm) {
txt += "1";
} else {
txt += i;
}
}
txt += '<br/>';
}
textBox.innerHTML = txt;
}
<input id="a">
<button onclick="makeSquare()">Input</button>
<div id="Text"></div>

Logic not firing correctly 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 6 years ago.
Improve this question
Edit: I've solved the problem by changing the 2d array to a simple array and using arithmetic and logic to get coordinates, see below.
I have an algorithm that adds 50 to a two dimensional array when the coordinates have an odd-odd pairing (e.g. [1][1], [3][5], etc). The only problem is, it isn't working. According to the browser console it never fires. This is what it is:
if(((col & 1) & row) == 1) { y+= 50; }
A fuller example of my code is here:
//goes through the board's array and calls
//drawChecker to print each found piece
function drawPieces() {
var row = 0;
var col= 0;
for(row = 0; row < 1; row++) {
var y = row * 100;
console.log("row " + row + " set x to " + x);
var flag = (row & 1);
for(col = 0; col < 8; col++) {
var x = col*50;
console.log("column " + col + " set y to " + y);
console.log("y was " + y);
if(((col & 1) & row) == 1) { y+= 50; }
console.log("Now y is " + y);
console.log("Done setting " + row + "," + col);
console.log("Final coordinates are " + x + "," + y);
drawChecker(x,y,square[row][col]);
}
}
}
The array was set up with the following code:
var square = new Array(4);
for(i = 0; i < 4; i++) { square[i] = new Array(8); }
You can not test the algorithms just on row 0.
function drawPieces() {
square.forEach(function (a, i) {
a.forEach(function (b, j) {
if (i & j & 1) {
square[i][j] = '#';
}
});
});
}
var square = Array.apply(null, { length: 4 }).map(function () { return Array.apply(null, { length: 8 }).map(function () { return '.'; }); });
drawPieces();
document.write('<pre>'+square.map(function (a) { return a.join(''); }).join('\n')+'</pre>');
So, I ended up switching my 2d array of 4x8 to a 1d array of 32 elements, and I changed the function to just this:
function drawPieces() {
for(i = 0; i < 32; i++) {
var value = square[i];
var x = (i % 4) * 100; //i%4 gets its column, 0-3
var y = Math.floor(i / 4) * 50; //i / 4 gets the row 0-3
if((i & 4) != 4) { x += 50; } //offset on even-numbered rows
drawChecker(x,y,value);
console.log(i + " has coordinates " + x + "," + y);
}
}

JavaScript - Commas as thousands separators [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Format numbers in JavaScript similar to C#
(17 answers)
Closed 8 years ago.
Can you help me changing that variable to make commas as thousand separators?
var number1 = 123456789;
$(function(){
document.getElementById("test").innerHTML("Var number1 is: " + number1); //i want that to display with commas
}
I don't understand answers on other questions like that. Thanks
You may look at some answers here:
http://www.queness.com/post/9806/5-missing-javascript-number-format-functions
but here's the code from the same page:
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
/**
* Usage: CommaFormatted(12345678);
* result: 12,345,678
**/

Categories