How to document.write multiple variables at once? - javascript

I have a loop that will declare a new variable each time. I want to write my results to a new window and I would like every string declared to print with breaks.
I did try making combining all vars together with '+' signs (using [i] to get the number of occurrences) but document.write printed it because it was a string.
Does anyone know what I can do? I'm sure there must be a few ways but I've been stuck on this for a while.
window['question'+i] = "some stuff";
var myWindow = window.open("", "Questions", "width=500,height=600");
myWindow.document.write(
question0 + ("<br>") +
question1 + ("<br>") +
question2 + ("<br>") +
question3 + ("<br>")
...
)

I recommend to not use different variables. Array's are made for these kind of things and provide functions to do this a lot easier. See this snippet below how to store the texts from a loop in an array and easy print it splitted by a <br> using the join function.
var values = new Array();
for (var i = 0; i < 10; i++) {
values.push("<span>value " + i + "</span>");
}
document.getElementById('result').innerHTML = values.join("<br>");
//If you really want to use document.write()
//document.write(values.join("<br>"));
<div id="result"></div>

Related

How do I put together string variables in Javascript? It's just saying "Object Undefined"

I have tried for so long to get this code to work. I'm programming a little game when you need to be fast, so I made a stopwatch. But the stopwatch just doesn't want to work. Instead of the seconds the stopwatch is showing Object Undefined and I don't know why. This is the code i'm using:
var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
stopwatchFrame+=1;
stopwatchSeconds = floor(stopwatchFrame/updatesPerSecond);
stopwatchSecondsString = toString(stopwatchSeconds);
var = "Total time: " + stopwatchSecondsString + " seconds";
I'm using a simple website called Koda.nu, it's a Swedish website for young to learn programming in JS. Some functions is coming from their built in source. I'm new to programming so that's why.
You are missing a variable name where you have a value of "Total time: " + stopwatchSecondsString + " seconds"; It should be:
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";
Also read what #Jaromanda X wrote in the comments section. It should be like this:
stopwatchSeconds = Math.floor(stopwatchFrame/updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
We don't have an access to your updatesPerSecond variable so that would throw an error as well. If declared, your code would work like this:
var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
var updatesPerSecond = 0;
stopwatchFrame += 1;
stopwatchSeconds = Math.floor(stopwatchFrame / updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";
You dont have a variable name in the last line, and if this is all your code, then you dont initialize updatesPerSecond, meaning you dont have a line like
var updatesPerSecond = somenumberhere
If you name your last variable and initialize updatesPerSecond then you should be fine.
However I dont know anything about this website, but I quess it's old. Here is some advice.
You need to tell javascript, that floor is a function from Math so use Math.floor, maybe it works in this website like you did, but keep in mind that you should use it otherwise.
toString() doesnt work like that. Again I dont know if they are using some different methods, but normal js toString() works like number.toString() and u can pass the radix as a parameter, meaning the base of the number representation (2 for binary, 16 for hexadecimal etc.) but this is optional, default is 10 for decimal.
Dont use var as a declaration. Use let instead, if the variable will change, and use const if it wont. In your case you should use let everywhere.
Other thing is that you can use the ++ operator to increment a value by 1, so instead of stopwatchFrame+= 1 just use stopwatchFrame++
And last you shouldn't initialize your default string value as "Nothing", it should be "", an empty string or undefined or null.
I hope this helps, have a good day!

Make javascript as function

i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/

How to get all the text separately from the bracket using javascript regular expression

I have a sentence stored in a variable.That sentence I need to extract into 4 parts depends on sentence which I have put into variables in my code,I can able to extract here and get into console but I am not getting the whole text of inside the bracket,only I am getting first words.Here is the code below.Can anyone please help me.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
SCRIPT
$(document).ready(function() {
regex = /.+\(|\d. \w+/g;
maintext = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
matches = maintext.match(regex);
text_split0 = matches[0].slice(0, -1);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];
text_split4 = matches[4];
console.log(text_split0);
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
console.log(text_split4);
$(".messages").append('<li>'+text_split0+'</li><li>'+text_split1+'</li><li>'+text_split2+'</li><li>'+text_split3+'</li><li>'+text_split4+'</li>');
// $("li:contains('undefined')").remove()
});
function buildMessages(text) {
let messages = text.split(/\d\.\s/);
messages.shift();
messages.forEach((v)=>{
let msg = v.replace(/\,/,'').replace(/\sor\s/,'').trim();
$('.messages').append(`<li>${msg}</li>`);
// console.log(`<li>${msg}</li>`);
});
}
let sentenceToParse = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
buildMessages(sentenceToParse);
Use the split function on the String, keying on the digits (e.g. 1.), you will get the preface and each of the steps into an array.
Use the shift function on the Array removes the unneeded preface.
Use forEach to iterate over the values in the array, clean up the text.
Using replace to first remove commas, then remove or with spaces on either side.
Use trim to remove leading and training whitespace.
At this point, your array will have sanitized copy for use in your <li> elements.
If you're only concerned with working through a regex and not re-factoring, the easiest way may be to use an online regex tool where you provide a few different string samples. Look at https://www.regextester.com/
Ok, Try another approach, cause regex for this isn't the best way. Try this:
$(document).ready(function() {
// First part of sentence.
var mainText = "Welcome to project, are you a here(";
// Users array.
var USERS = ['new user', 'test user', 'minor Accident', 'Major Accident'];
var uSize = USERS.length;
// Construct string & user list dynamically.
for(var i = 0; i < uSize; i++) {
var li = $('<li/>').text(USERS[i]);
if(i === uSize - 1)
mainText += (i+1) + ". " + USERS[i] + ")";
else if(i === uSize - 2)
mainText += (i+1) + ". " + USERS[i] + " or ";
else
mainText += (i+1) + ". " + USERS[i] + " , ";
$(".messages").append(li);
}
console.log(mainText); // You will have you complete sentence.
}
Why that way is better? Simple, you can add or remove users inside the user array. String together with your user list will be updated automatically. I hope that help you.

how to set the values of one array to another array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying array by value in javascript
I am a beginner with javascript, so I would really appreciate any help or advice. I'm trying to get the values that I collect with my inputs array (that are put into a form, by the user, in the document) to set them to the words array. So, I would like inputs[0] = words[0], inputs[1] = words[1] etc. I thought by setting words to an empty array, and then to equal the index value of inputs, that I would achieve this, but it's not working. Words keeps showing up as "undefined".
function goMad() {
var words = [];
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length - 1; i++) {
inputs[i].value = words;
}
var story = words[0] + "! he said " + words[1] + " as he jumped into his convertible " + words[2] + " and drove off with his " + words[3] + " wife.";
document.getElementById("story").innerHTML = story;
console.log(words[0]);
}
Instead of this line:
inputs[i].value = words;
You can use:
words.push(inputs[i].value);
This will add the provided value to the words array. See the MDN docs.
As #pimvdb and #Shmiddty have pointed out you could also use the following. This would behave exactly the same as using push:
words[i] = inputs[i].value;

javascript for() loop, split(), and array question

Ok I've been asking alot of JS questions lately, and realized I just need to go learn it.
Been following tutorials at http://www.tizag.com/javascriptT very simple and straightforward.
I just want to make sure I understand this correctly. It took me a while to get it:
<script type="text/javascript">
var myString = "zero one two three four";
var mySplitResult = myString.split(" ");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
}
</script>
-
var myString = "zero one two three four";
Obviously that creates a simple string variable.
var mySplitResult = myString.split(" ");
That splits it using " " as the delimeter, and assigns it to the mySplitResult array. Correct? Or is it not an array?
for(i = 0; i < mySplitResult.length; i++){
Is this saying the number of values in the array? Doesn't seem like it could be saying the actual length of characters in the string.
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
This just returns mySplitResult[i] variable "i". Since i is increasing with each loop, it pulls the correct information from the array.
Your understanding is essentially correct. One thing you should do is declare all your variables: this is particularly important inside functions. So, you should declare i as a variable, either before the loop:
var i;
for (i = 0; i < mySplitResult.length; i++) {
... or in the first expression in the for statement:
for (var i = 0; i < mySplitResult.length; i++) {
Your analysis is correct, but you should see that by just testing it. Use Firebug extension with Firefox and you can step through your javascript.
This will help you understand what is going on, as you can then look at properties of the element and monitor what is actually happening.

Categories