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>";
}
Related
For my Javascript course I got this code:
for (var i in window.navigator)
{
document.getElementById('divResult').innerHTML +=
i + ': ' + window.navigator[i] + '<br />';
}
</script>
The teacher (online) wants me to limit the results into maximal 10.
For me this is a big puzzle. From other questions about the for..in I think to know it is a discussable statement. But how to approach this for..in? As an array with i.length?
Just set a counter. In each iteration you increase the counter and when the counter reaches 10 you simply break out of your loop
Code:
// Since we're going to access this div multiple times it's best to
// store it outside of the for loop.
var output = document.getElementById('divResult');
var counter = 0;
for (var elem in window.navigator) {
var value = window.navigator[elem];
output.innerHTML += counter + ': ' + elem + '=' + value + '<br />';
++counter;
if (counter == 10) {
break;
}
}
Since you're new to JavaScript I would like to explain a little bit about for-in
If you want to get a specific value from an array you access it's element by index. So for example:
var myArray = [7, 5, 6, 6];
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i];
}
But now you want to loop through window.navigator and this element is not an array but a object. And since a object is key-value it does not have a index. So how do you loop through it?
Let's imagine window.navigator looks like this:
var navigator = {
myBrowser: 'Google Chrome',
myOtherProperty: 'otherValue',
AnotherProperty: 'anotherValue'
};
If we want to get the first element from our object we use
navigator.myBrowser
or
navigator['myBrowser'];
Now we want to loop through all the elements in our object. Since the normal for loop uses a index and objects don't have indexes we use the for in loop. This loop iterates through all the properties of our object and gives us the key.
for (var key in navigator) {
// Here we access a property in our object by the key given by our for loop.
var value = navigator[key];
}
So the first iteration our key is myBrowser and the value is Google Chrome
The next iteration the key is myOtherProperty and the value otherValue.
It is usually a good idea to use hasOwnProperty if you're looping through an object:
for (var key in navigator) {
if (navigator.hasOwnProperty(key) {
var value = navigator[key];
}
}
Hope this helps
The teacher came back with an answer for my for..in array problem:
<script>
var navigatorArray = [];
for (var i in window.navigator) {
navigatorArray.push(window.navigator[i]);
}
navigatorArray.sort();
console.log(navigatorArray);
var htmlString = '';
for (var j = 0; j < navigatorArray.length; j++) {
htmlString += navigatorArray[j] + '<br />';
}
with the .push habbit it should be possible to collect them in an array and index them.
I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.
What I'm trying to do is take a comma separated string like "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress" - split that string into and array and write a loop that outputs each array item on a separate line.
This works:
function splitstr() {
var splitStr = "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress";
var output = splitStr.split(',');
for (var i = 0; i < output.length; i++) {
document.write(output[i] + "<br />");
}
}
but obviously it outputs to a blank page. I need it to output the results into a div.
So I try the following code but it doesn't work. It only prints out the last one "Wordpress".
function splitstr() {
var splitStr = "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress";
var output = splitStr.split(",");
for (var i = 0; i < output.length; i++) {
document.getElementById("splitres").innerHTML = output[i] + "<br />";
}
}
what am i doing wrong?
agon
document.getElementById("splitres").innerHTML += output[i] + "<br />";
Note +. With that, you are appending HTML; without it, you are overwriting it.
Can someone please tell me why when I click on the [s] href created next to the list of names (myhand) generated it always says selection and i are 5?
var printDD = function(myhand, mydiv){
var dtext = "";
for(var i = 0; i < myhand.length; i++){
dtext += '[s]' + myhand[i] + ', ';
}
mydiv.html(dtext);
for(var i = 0; i < myhand.length; i++){
$('#dd'+i).click(function(){
selection = i;
console.log("sel: " + selection + " i: " + i);
});
}
}
You want to take a look at JavaScript closure inside loops – simple practical example. As the answer to that question says, you can create a function to return one, or you can use inline function invocation in the for loop like so:
for(var i = 0; i < myhand.length; i++) {
$('#dd'+i).click((function(x) {
return function () {
selection = x;
console.log("sel: " + selection + " x: " + x);
}
}(i)));
}
Because the value of i is determined at the time the click handler is run. So it will always have the value of myhand.length - 1, which is the state you left i in after the for-loop.
I am having trouble with output of an array, I think.
What I would like the output to look like is:
1. FirstName LastName DOB
but what I end up with is:
1. FirstName
2. LastName
3. DOB
Here is what I have so far but I am not seeing what I am doing wrong.
// global variable:
var tasks = [];
// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
'use strict';
// Get the task:
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
var dob = document.getElementById('dob');
// numerical value of dob
var dateofBirth = new Date(dob.value);
// Reference to where the output goes:
var output = document.getElementById('output');
// For the output:
var message = '';
if (firstName.value && lastName.value && dob.value) {
// Add the item to the array:
tasks.push(firstName.value, lastName.value, dateofBirth.toString());
// Update the page:
message = '<h2>Persons Entered</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li>' + tasks[i] + '</li>';
}
message += '</ol>';
output.innerHTML = message;
} // End of IF.
// Return false to prevent submission:
return false;
} // End of addTask() function.
// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;
Thanks, I hope this helps you to help me.
tasks.push({firstName: firstName.value, lastName: lastName.value, DOB: dateofBirth.toString()})
And then
tasks[0].firstName will output firstName.value
tasks[0].lastName will output lastName.value
etc..
Edit
Using this, you can then construct your messasge like this :
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li><span>' + tasks[i].firstName + '</span><span> '
+ tasks[i].lastName + '</span><span>' + tasks[i].DOB + '</span></li>';
}
Of course, the span tags are optionnal but this will allow you to apply a style to each part of the information in your css (width, padding, etc..) and you will always be able to easily select a property of a task by index
Your problem is that you're adding li elements to every element in your array, instead only add teh li once
// Update the page:
message = '<h2>Persons Entered</h2><ol><li>' + tasks.join(' ') + '</li></ol>';
output.innerHTML = message;
Why do you put each element in its own <li>?
If you don't put it in different <li> but in a common one, everything will be fine
message = '<h2>Persons Entered</h2><ol><li>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += tasks[i];
message += " ";
}
message += '</li></ol>';
output.innerHTML = message;
Use Span. you can use Array.join
output.innerHTML= '<h2>Persons Entered</h2><div><span>' + tasks.join("</span> <span>") +"</span>";
You want to add them as an array to the array, not as values to the array
What you have is this:
tasks.push(firstName.value, lastName.value, dateofBirth.toString());
what I think you want is this:
tasks.push([firstName.value, lastName.value, dateofBirth.toString()]);
The answer above is the same, but with an object, not a array.
What you are doing is pushing multiple values into your array. What you want to be doing is to turn the different values into a single value and then push that value into your array. To get the exact output as you were requesting, you can turn these multiple values into one by concatenating them into a string:
Change this:
tasks.push(firstName.value, lastName.value, dateofBirth.toString());
Into this:
tasks.push(firstName.value + ' ' + lastName.value + ' ' + dateofBirth.toString());
However, this does mean you'll lose access to the individual values. If you want access to those, you could instead assemble them into an object:
tasks.push({"firstName" : firstName.value,
"lastName" : lastName.value,
"dateOfBirth" : dateofBirth.toString());
Its a little confusing what you are asking. If you simply want this:
1. FirstName LastName DOB
over this:
1. FirstName
2. LastName
3. DOB
Then your issue is not with the array but with how you are defining the loop code. Try this instead:
// Update the page:
message = '<h2>Persons Entered</h2><ol><li>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += tasks[i] + ' ';
}
message += '</li></ol>';
That way you are putting the array elements in a single list element, rather than across three of them.
EDIT - for Multi-dimensional array traversal
This is assuming that the array is defined this way (per Dan Steingart's answer):
tasks.push([firstName.value, lastName.value, dateofBirth.toString()]);
We then can have the following:
// Update the page:
message = '<h2>Persons Entered</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li> + tasks[i].toString().replace(',',' ') + '</li>';
}
message += '</ol>';
Here you are traversing each element of tasks when each element of tasks is also itself an array. The toString() on an inner array will display the values in a comma separated fashion, then the replace() function simply replaces the comma's with spaces.