for loop for 0 to n number with digits specification - javascript

How can I write a for loop for 16 digit number from 0 to n
I want the output to be like:
0000000000000000
0000000000000001
0000000000000002
0000000000000003
0000000000000004
0000000000000005
Tried this but this isn't working:
for(i = 0000000000000000; i < 0000000000000010; i++){
$("#TestDiv").append(i);
}
check out the JSfiddle

Have a look at using the slice method. For example:
var addLeadingZeros = function(number){
var str = "0000000000" + number; // add leading zeros for single digit number
return str.slice(-10); // slice the whole number down from the end
}
for(var i = 0; i < 100; i++){
$("#TestDiv").append(addLeadingZeros(i));
}

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function writeNumber(n){
var nLen = n.toString().length;
var zeroLen = 16-nLen;
var arr = [];
var str = "0";
for(var z=0;z<zeroLen;z++){
arr.push(str);
}
arr.push(n.toString());
return arr.join('');
}
window.onload = function () {
var arr = [];
for(i=0;i<11;i++){
var str = writeNumber(i);
arr.push(str);
}
document.getElementById("testDiv").innerHTML = arr.join('<br>');
};
</script>
<div id="testDiv"></div>
</body>
</html>
More efficient with an array. Maybe it doesn't matter so much when the loop is just 10 items, but you're going to write to the DOM 10 times if you access the DOM inside the loop instead of outside the loop just 1 time. All the
small things adds up, so it may matter.
9. Stop touching the DOM, damnit!

That won't work because for number 00000001 is equal to 1 . You've to use strings.
Use like bellow
var str = '';
var zeros = '0000000000000000'; //string of 16 0's
for(i=0;i<11;i++){
var temp = zeros.slice(i.toString().length); // get the 0's 16-length of i
str += temp+i+'<br>';
}
$("#TestDiv").append(str);
DEMO

Related

Javascript insert space at nth position in string

Let's say I have the following string: "Stackoverflow", and I want to insert a space between every third number like this: "S tac kov erf low" starting from the end. Can this be done with regexes?
I have done it the following way with a for-loop now:
var splitChars = (inputString: string) => {
let ret = [];
let counter = 0;
for(let i = inputString.length; i >= 0; i --) {
if(counter < 4) ret.unshift(inputString.charAt(i));
if(counter > 3){
ret.unshift(" ");
counter = 0;
ret.unshift(inputString.charAt(i));
counter ++;
}
counter ++;
}
return ret;
}
Can I shorten this is some way?
You could take a positive lookahead and add spaces.
console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));
You can use Regex to chunk it up and then join it back together with a string.
var string = "StackOverflow";
var chunk_size = 3;
var insert = ' ';
// Reverse it so you can start at the end
string = string.split('').reverse().join('');
// Create a regex to split the string
const regex = new RegExp('.{1,' + chunk_size + '}', 'g');
// Chunk up the string and rejoin it
string = string.match(regex).join(insert);
// Reverse it again
string = string.split('').reverse().join('');
console.log(string);
This is a solution without regexp, with a for...of
<!DOCTYPE html>
<html>
<body>
<script>
const x="Stackoverflow",result=[];
let remaind = x.length %3 , ind=0 , val;
for(const i of x){
val = (++ind % 3 === remaind) ? i+" " : i;
result.push(val);
}
console.log(result.join(''));
</script>
</body>
</html>

Return array type from stack or table - Javascript

I have a problem with my code. Maybe simple, maybe not - for first lets look at this.
var tab = [];
do{
var i = 0;
tab.push(prompt("Write some type of array!"));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++)
document.write(typeof(tab[i])+"<br>");
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta charset="utf-8">
<meta name="author" content="Donio3d">
</HEAD>
<BODY>
</BODY>
<script src="script.js"></script>
</HTML>
So i want to return a type of array from stack. Everything is always a string.
Is there any way to do this, without checking by IF statement?
To get the typeof of the input you have to first checking if it is a number using Number.isNaN() and for simplicity also used Unary plus (+) operator.
Code:
const tab = [];
const getInputTyeof = i => typeof (!Number.isNaN(+i) ? +i : i);
do {
tab.push(prompt('Write some type of array!'));
} while (confirm('Next array?'));
tab.forEach(input => document.write(getInputTyeof(input) + '<br>'));
Since promt will always return a string in your example you have to figure out if the input may represent a other type or not, using something like this:
var tab = [];
do{
var i = 0;
tab.push(parseType(prompt("Write some type of array!")));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++){
document.write((typeof tab[i])+"<br>");
}
function parseType(e){
if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
return parseFloat(e);
}
return e;
}
prompt will always return you a string type so you need to make a custom logic with isNaN() to separate out the string and integer values. Something like this below:
var tab = [];
do{
var i = 0;
tab.push(prompt("Write some type of array!"));
i++;
}while(confirm("Next array?"));
var integerType = [];
var stringType = [];
for (var i=0; i<tab.length; i++){
if(isNaN(tab[i])){
stringType.push(tab[i]);
} else {
integerType.push(tab[i]);
}
}
console.log('Integer type array ' + integerType);
console.log('String type array ' + stringType);
var tab = [];
do{
var i = 0;
tab.push(parseType(prompt("Write some type of array!")));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++){
document.write((typeof tab[i])+"<br>");
}
function parseType(e){
if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
return parseFloat(e);
}
return e;
}
Hey! That is exacly what i was looking for. Thanks for help!

JavaScript Nested While Loop, Loops infinitely

So I'm trying to create a loop that will reduce any number put into it to a single digit. The way I'm doing my math is adding each number up one by one. In this case 9+9+9+9+9+9+9+9+9+9+9+9=108. I want it to run through and check that 108 is still greater than 9 and do it till the result is less than 9. It just gets stuck in a loop. I've also tried some variants that will return NaN.
<html>
<body>
<h1>Reduce Loop</h1>
<p id="Result"></p>
<script type="text/javascript">
//Defined var start
var Result = 0;
var TempReduce1 = 0;
var LoopTempLength = 0;
var LoopTempString;
var i = 0;
//Defined var end
//The LongNumber variable represents user input
var LongNumber = 999999999999;
//Converts LongNumber to a integer
var LoopTemp = parseInt(LongNumber);
//Check if LoopTemp is greater than 9; it is
while (LoopTemp > 9) {
//Gets the Length of LoopTemp by converting it to a string and grabbing the length to then convert back to a integer
LoopTempLength = parseInt(LoopTemp.toString().length);
//Converts LoopTemp to a string for manipulation
LoopTempString = LoopTemp.toString();
i = 0;
//Check to see if i is less than the length of LoopTempLength
while (i < LoopTempLength) {
//Grabs the number in relationship to i, converts it to a integer and added it to TempReduce1
TempReduce1 += parseInt(LoopTempString.charAt(i));
i++;
}
LoopTemp = TempReduce1;
}
Result = LoopTemp;
document.getElementById("Result").innerHTML = Result;
</script>
</body>
</html>
So Patrick Evans has it right. I inserted
TempReduce1=0;
in your code after the line
i=0
and the routine kicked out 9 as one would expect.

Push method displayed incorrectly

I have an issue with this code. I want to push the odds number in a array called number. But when I display it with document.write it doesn't print out the way it supposed to. Please help!!
Here's what it displays: 11,31,3,51,3,5,71,3,5,7,9 instead of: 1,2,3,4,5,6,7,8,9
<!DOCTYPE html>
<html>
<head>
<title>Trial</title>
</head>
<body>
<script>
var number = [];
var i;
for (i = 0; i < 5; i++) {
var x = 2 * i + 1;
number.push(x);
document.write(number)
};
</script>
</body>
</html>
Put documet.write() after for loop. You are actually writing array of numbers at each stage.
var number= [];
var i;
for (i=0; i<5; i++)
{var x =2*i+1;
number.push(x);
};
document.write(number)

Forming an inverted ascii triangle art using JS looping

Without nesting loops, how are you able to form such an ascii art?
####
###
##
#
This is what I currently have:
function invertTriangle (row) {
var asteric = "*" * row;
for ( var y=row; y>=row; y--){
asteric = asteric - "*";
console.log(asteric);
}
};
invertTriangle(10);
I will appreciate your help and explanation!
Thank you!
Try:
var string = "";
for (var i = 0, j = 4, k = 4; i < 10; i++) {
string += "*";
if (--j === 0) {
j = --k;
string += "\n";
}
}
alert(string);
Hope that helps.
Here's a way of doing it with recursion.
Basically, you call the function with the number of chars you'd like printed on the first line. It then constructs a string with this many characters in it. It then decrements the number of chars wanted and, if this number is greater than 0, calls itself again and adds the new result to the current result. This continues until we get to a line that requires zero characters. At this point, the function no longer calls itself and the fully constructed string is returned to the original caller.
Code:
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('triTgt').innerText = makeTriString(40);
}
function makeTriString(nStars)
{
var str = '';
for (var i=0; i<nStars; i++)
str += "*";
str += "\n";
nStars--;
if (nStars > 0)
str += makeTriString(nStars);
return str;
}
</script>
<style>
</style>
</head>
<body>
<div id='triTgt'></div>
</body>
</html>

Categories

Resources