I'm fine with understanding what is happening in the console.log but I want to display the code in the browser window. I think I should use document.write but I am unsure about this.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
},
steve: {
firstName: "Steve",
lastName: "Gates",
}
};
var list = function(friends){
for (var key in friends){
console.log(key);
}
};
var search = function(name){
for (var key in friends){
if (friends[key].firstName === name){
console.log(friends[key]);
return friends[key];
}
}
};
You could use the alert
function
alert("Hello World")
or you could use
document.write("Hello World")
which outputs the string "Hello World" to the position of the js snippet in the html. Alternatively, you could manipulate the DOM and set innerHTML
on a div
or span
tag. If you add a tag with an id to your html like so,
<span id="foo"></span>
you can set the html contents with
document.getElementById("foo").innerHTML = "Hello World"
Of course, if your problem is to serialize the result of your function, use JSON.Stringify
alert(JSON.stringify({"hello": "world", 3: "bar"}));
In order to show your hash you can use document.write, but you need to "stringify" your data like that :
document.write(JSON.Stringify(friends));`
And if you would like something more beautiful :
document.write(JSON.stringify(friends, null, "<br/>"))
Documentation : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Another possibility is to use jQuery's .html() to modify an existing HTML element on your page.
var showFriends=function(){
var x = JSON.stringify(friends,null,'</br>');
$('#myDiv').html('<p>'+x+'</p>');
};
jsfiddle: http://jsfiddle.net/wLZff/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.