Reputation: 1566
Ok, embarrased to be asking such a basic question but here goes. And yes, I googled it, but for some reason the light bulb doesn't go off.
So, here's a sample code:
var name = "Oy Vey";
for(var i = 0; i < name.length; i++) {
return name[i];
};
How do I output that in the browser's console?
Or print out the results on a web page?
(yes, I know, basic question. please be kind)
Upvotes: 0
Views: 124
Reputation: 2210
Change this line:
return name[i];
To this line:
console.log(name[i]);
Upvotes: 1
Reputation: 122
in your case
for(var i = 0; i < name.length; i++){
console.log(name[i]);
}
to put the output in current page check
getElementById
getElementsByTagName
getElementsByClassName
for more w3Schools
Upvotes: 0
Reputation: 8921
You can use console.log
to write things to the console:
for(var i = 0; i < name.length; i++) {
console.log(name[i]);
};
Another way to check values is to use alert()
, which will show the value you provide it in a dialog box:
if (name != 'bob') {
alert("Access denied");
}
Showing the data in your page is more complicated. A couple of quick ways are by manipulating the DOM directly:
document.getElementById("myparagraph").innerHTML = name;
Or with JQuery:
$("#myparagraph").text(name);
Both of these methods rely on an element (with ID myparagraph
, which you can change to whatever you like) which can hold the text. Ideally it would be a <p>
, <span>
, or heading.
Upvotes: 0
Reputation: 4360
If you use return
statement in your looping you only get the first result of your iteration remember that. You can use console.log()
or you can use html to render result, something like this:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript output</h2>
<p id="demo"></p>
<script>
var name = "Oy Vey";
var leng_name = "";
var i;
for (i = 0; i < name.length; i++) {
leng_name += i +
"<br>";
}
document.getElementById("demo").innerHTML = leng_name;
</script>
</body>
</html>
Upvotes: 0
Reputation: 303
you can use console.log(name[i])
to print in console from inside the array. for printing results on webpage you will need to do something like this:
var name = "Oy Vey";
for(var i = 0; i < name.length; i++) {
document.body.innerText += name[i] // print data in body
console.log(name[i]); // print data in console
// return name[i]; // gives an error if not used in a function
};
you can also user alert("dummy_string")
to alert the data.
Upvotes: 0