Javascript - Display array elements - javascript

I am trying to run a simple Javascript to display the elements of an array that I create by splitting a string. The code is as follows:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "01/01/2016";
var parts = text.split("/");
var i;
for (i = 0; i < parts.length; i++) {
var x += parts[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
The above code does not display anything on the browser and I can't for the life of me figure out where the error is. Can someone advise?

This line is tricky, so any JavaScript compiler would complaint:
var x += parts[i] + "<br>";
Uncaught SyntaxError: Unexpected token +=
You can't declare a variable with the "+=" assignment operator.
Let's rewrite this assignment:
var x = x + parts[i] + "<br>";
When it works, the result is the same. Only that the first time this runs, x is undefined, not initialized yet. Concatenating undefined to any a string will contain the string undefined in the result.
But does it re-declare the variable? No, because a concept called hoisting, any variable declaration, even inside a loop, is pushed to the top of the scope, in this case the global scope. (We're not talking about let and const)
To solve that, before you read from this variable, you need to definitely assign to it, i.e. initialize.
var x = '';
Later you'll be able to use the operator +=, and then you don't need to use the var keyword.

fgil give you good answer - you declare x variable in loop, at the first - it's not initialized (you have get error on += ), and second - you reset variable each iteration by declaring it at the loop. But I think that this loop is not needed. You can make code more simple and short if you will use method join of Array. Look at this:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "01/01/2016";
var parts = text.split("/");
var x = parts.join("<br>") + "<br>";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Here fiddler with sample
You can do it in one line:
document.getElementById("demo").innerHTML = "01/01/2016".split("/").join("<br>") + "<br>";

you are just failing in a basic concept. var x must be declared before the loop, like this:
var x = '';
for (i = 0; i < parts.length; i++) {
x += parts[i] + "<br>";
}

Define x outside the for loop.
var text = "01/01/2016";
var parts = text.split("/");
var x = "";
for (i = 0; i < parts.length; i++) {
x = x + parts[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;

Related

Javascript - Dynamic variable

I am having problem to figure correct syntax to make those Javascript dynamic variable works:
I want to replace this code:
<code>
var res1 = res0.replace('[a1]', a1);
var res2 = res1.replace('[a2]', a2);
(...)
var res7 = res6.replace('[a7]', a7);
</code>
With something dynamic, like
<code>
for (var i = 1; i < 8; i++) {
**var str2 ="res" + i + " = res + i + .replace('[a + 'i']', window['a' + i])";**
eval(str2);
}
</code>
The ElementID is recovered from another Dynamic Variable, that works
<code>
for (var i = 1; i < 8; i++) {
var str ="a" + i + " = document.getElementById('a'+i).value";
eval(str);
}
</code>
General idea is simple.
Capture from a form, (input type text) and replace the strings called [a1], [a2], etc inside a textarea. Code works without dynamic variables.
Any idea is more than welcome.
Thank you
so don't use eval... bad practice, much bugs, little security, unexpected results...
it sounds like you just need an array.
(if you are using a for loop and eval - chances are you really want an array instead).
here is code that does not use eval()
reses = [] // of res0, res1 etc
for (let i = 1; i < 8; i++) {
reses[i].replace(`[a${i}]`, window[`a${i}`]);
}
for (let i = 1; i < 8; i++) {
let element =document.getElementById(`a${i}`).value;
}

How do i loop a function

I am learning javascript at the moment and i want to ask you about an exercise that i'm trying to finish. This is the quiz i should finish:
https://classroom.udacity.com/courses/ud803/lessons/a7c5b540-51a6-44dc-b2f2-515c9dd6ca4f/concepts/c746623a-eefd-4518-9890-2c5f320b0282
and here is my code. I just dont understand what im doing wrong . can someone explain me.
<html>
<head></head>
<body>
<script>
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
return x;
x++;
}
}
document.write(buildTriangle(10));
</script>
</body>
</html>
I would like to know what i did wrong and how i can fix it, because i always get either "undefined" or nothing at all.
Also i know it's probably a simple mistake but i'm still a beginner so.
after a return statement, any instruction never executed
You have a few issues in function buildTriangle(widest).
var x = makeLine(1);
This will always set x to makeLine(1) doing x++ in the while loop will do nothing.
Further more the x++ is after a return statement so the code will never reach it.
Hope this helps a little.
It's how you actually write the * on your document. I've modified how your buildTriangle works and kept makeLine intact.
(function() {
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "<br/>";
}
function buildTriangle(widest) {
for(var x = 1; x <= widest; x++){
// Moved write inside the loop
// since you want to write each line here
document.write(makeLine(x));
}
}
buildTriangle(10);
})();
<html>
<head></head>
<body>
</body>
</html>
change your function to this
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
// putting return here would make function execution to stop
// and return the value to the callee, thus not executing
// any statement after this.
x++;//this making this an unreachable code
}
return x;
}
You're almost there.
For the makeline() function, just remove \n so it looks like this:
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line
}
For buildTriange() you have a few issues: 1) var x = makeLine(1); means that x will always be equal to *, because that is was makeLine(1) will return; 2) the return statement makes x++ unreachable.
Consider this:
function buildTriangle(widest) {
var output = '';
var x = 1;
while(x <= widest){
output += makeLine(x) + '<br>';
x++
}
Now, it build an output. The x variable is a counter. While x is 1 it will add to the output the result of makeLine(1) + '<br>', then it will increase by 1 and run again until the value of x is the same as widest. Then it will return output.
Since document.write() writes html and not plain text. You have to use the line break, not a newline.

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>

First element in object is undefined using += operator

I have a problem to use the operator += in an object.
Because i have to change the variable dynamically i use an object as variable.
But if i use the += operator the first element in the output always gets undefined. I think thats because the object is initialized empty.
What is the best solution to prevent to output that element ?
Here goes my example code:
var dynamicVariable = {};
var group = "apples";
for(var i = 1; i<5; i++)
{
dynamicVariable[group] += " Apple" + i + "<br>";
}
document.getElementById("fruits").innerHTML = dynamicVariable[group];
jsFiddle
This is happening because dynamicVariable[group] has the value undefined before you start appending to it. undefined + " Apple1" is "undefined Apple1".
You need to initialize it to an empty string first:
dynamicVariable[group] = "";
for(var i = 1; i<5; i++) {
dynamicVariable[group] += " Apple" + i + "<br>";
}

Programmatically setting the name of a variable

Is there a shortcut for writing the following 100 assignments?
variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
...
variable_100 = 100;
I have tried
for(var i = 1; i <= 100; i++) {
variable_ + i = i;
}
but I get the error message "Invalid left-hand side in assignment". Any ideas?
Here are a few methods:
Method 1: use eval
Here is the most direct method:
for(var i = 1; i <= 100; i++) {
eval("var variable_" + i + " = " + i);
}
variable_1; // => 1
Disclaimer for the above method: I don't think this problem is a good candidate for using eval. If you do use eval, you should never allow user input to go into what you are evaling, or you could open your site to security risks. That mistake is the main reason people say eval is evil.
Method 2: use dynamically generated object properties
This is a much, much better way:
// If you want these variables to be global, then use `window` (if you're
// in a browser) instead of your own object.
var obj = {};
for(var i = 1; i <= 100; i++) {
obj["variable_" + i] = i;
}
obj.variable_1; // => 1
About the note in the comment about using window to create global variables: I would recommend against this, as it is a quick way to pollute your global scope and step on variables unwittingly.
Method 3: use an array
David suggested using an array. This is another great idea, and, depending on what you are trying to do, may be preferred:
var arr = [];
for(var i = 1; i <= 100; i++) {
arr.push(i);
}
arr[0]; // => 1
This will do it:
for(var i = 1; i <= 100; i++) {
eval("variable_" + i + " = " + i + ";");
}
eval is basically evil, but for such purpose it's OK to use it. (reference)
Live test case.
You are better off using an array
var variable = [];
for (var i=1; i <= 100; i++) {
variable[i] = i;
}
Later, you can access the values using variable[1], variable[2] etc.
If it is like that why not to define array of the objects
var a = new Array();
for(i=0;i<100;i+=)
a[i] = i;
Why not using an array instead like this?
<script language="javascript">
var arrayVar = new Array();
for (var i=0; i<100; i++) {
arrayVar["variable_" + i] = i;
}
</script>
Use an array:
var variable = [];
for(var i = 1; i <= 100; i++) {
variable[i] = i;
}
By way of analogy, you'd want to use an array instead of 100 variables for the same reason you'd want
<div class="variable"></div>
<div class="variable"></div>
<div class="variable"></div>
//and so on
instead of
<div id="variable_1"></div>
<div id="variable_2"></div>
<div id="variable_3"></div>
//and so on
<div id="variable_100"></div>
Invalid left-hand side in assignment
This error gets generated because variable_ + i is an expression. The interpreter thinks you are trying to add two variables instead of concatenating a variable name and a string. An expression cannot be on the left-hand side of an assignment operation.
for(var i = 1; i <= 100; i++) {
window["variable_" + i] = i;
}
alert( variable_50 );
alert( variable_34 );
Assuming you're on a browser you can do:
global[variable] = 'hello'
console.log(variable) -> hello

Categories

Resources