Push method displayed incorrectly - javascript

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)

Related

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/For Loop/Basic code/Only runs once

first off yes, I did look at many other codes on this topic and none of those are like mine. I have a very basic code so I apologize if I missed something obvious but I cannot understand why my code will only show one number.
Here is the code.
<!DOCTYPE html>
<head>
</head>
<body>
<div id="test"></div>
<script>
var wildCard = (Math.floor(Math.random() * 5) + 1);
var temp = 1;
for (var i=0; i < 5; i++){
document.getElementById("test").innerHTML = wildCard + "<br />";
temp++;
}
</script>
</body>
</html>
Very basic code, however the only thing is that I only get one random number printed instead of 5 going down in a vertical line. I would like to know what I am missing as to why it will not loop.
Reason why only one number gets printed instead of five is because the DOM node with id test's inner html is replaced in every iteration. When the for-loop ends, you only see the value of the last iteration.
You can use createTextNode and appendChild to complete this task as follows:
var temp = 1;
for (var i=0; i < 5; i++){
const wildCard = (Math.floor(Math.random() * 5) + 1);
const textNode = document.createTextNode(wildCard);
const testDiv = document.getElementById("test");
testDiv.appendChild(textNode)
testDiv.appendChild(document.createElement("br"));
temp++;
}
Generate a new random number in each iteration of the loop, and then assign the full HTML once, after the loop has finished.
<script>
var temp = 1;
var html = "";
for (var i=0; i < 5; i++) {
var wildCard = (Math.floor(Math.random() * 5) + 1);
html += wildCard + "<br/>";
temp++;
}
document.getElementById("test").innerHTML = html;
</script>

JavaScript Looping Through Array, Combining After [duplicate]

This question already has answers here:
Javascript split, push and join
(2 answers)
Closed 6 years ago.
I get a string of data back that is seperata by semi colons. Here is an example:
apple;orange;lemon).
I am trying to strip out the semi colons and turn the string into an array, so I can access each item individually. Then, I am trying to join them back together and print them out on the screen separated by a "/". The problem is that it is not working.
var planArray = associatedAction.split(";")
for(var i=0; i < planArray.length; i++) {
var seperatedActionPlan = planArray[i];
}
Also, I would like to put the final output into a variable, so I can print out just that variable on the page.
Please help!
EDIT!
One thing I forgot to mentioned, is that when the string prints out, I want the values to be separated. So as an example I want the final print out to be Apple/Orange/Lemon
I think this is what you are looking for:
<script type="text/javascript">
var associatedAction = "a;b;c;d";
var planArray = associatedAction.split(";")
var seperatedActionPlan = '';
for (var i = 0; i < planArray.length; i++) {
if (i < planArray.length - 1) {
seperatedActionPlan =
seperatedActionPlan.concat(planArray[i] + "/");
}
else {
seperatedActionPlan = seperatedActionPlan.concat(planArray[i]);
}
}
alert(seperatedActionPlan);
</script>
this should work
var seperatedActionPlan = planArray.join("/")
let seperatedActionPlan = associatedAction.split(";").join("/"));
Should do it.
Change your code to this:
var planArray = associatedAction.split(";"),
seperatedActionPlan;
for(var i=0; i < planArray.length; i++) {
// ... do what you need
}
seperatedActionPlan = planArray.join('/');
// print out seperatedActionPlan
or if you don't do anything to the array except splitting and joining with / just use
var seperatedActionPlan = associatedAction.replace(';', '/');
// print out seperatedActionPlan
This help you :
<html>
<head>
</head>
<body>
<script>
var associatedAction = "apple;orange;lemon";
var planArray = associatedAction.split(";")
for(var i = 0; i < planArray.length; i++ ) {
var a = document.createElement('a');
var txt = document.createTextNode("/");
a.href = "#";
a.innerHTML = planArray[i];
document.body.appendChild(a);
if (i != planArray.length - 1)
a.insertAdjacentHTML('afterend',"/");
}
</script>
</body>
</html>

Javascript Addition Program

This is a javascript program for adding two numbers but the problem is the code is too big and everytime I need to change the number to the integer by parseInt so if I need to add more numbers the code will become more lengthy. How can I make it more simple?
<!DOCTYPE html>
<html>
<head>
<title>adding</title>
</head>
<body>
<script type="text/javascript">
var x;
var y;
var z;
var n;
var result;
x=prompt("1st number");
y=prompt("2nd number");
z=parseInt(x);
n=parseInt(y);
result= n + z;
alert(result);
</script>
</body>
</html>`
`
create a js function:
function addNumbers(arr) {
var result = 0;
for (var i = 0; i < arr.length; i++){
result += parseInt(arr[i]);
}
return result;
}
function evaluate(){
var numberArray = document.selectElementById("numbers").value.split(",");
alert(addNumbers(numberArray));
}
and add a html input field:
<input id="numbers"/>
<button onclick="evaluate()"></button>
this will add all numbers you typed into the input field (comma seperated)
note:
this will only work with valid inputs, i.e.:
1,2,4,-8 would work
1 2,5,2 would not work
e,2,3 would not work

for loop for 0 to n number with digits specification

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

Categories

Resources