2016-02-19 78 views
1

我是新手編程,並試圖從頭開始創建一個博客,不僅對我的編碼技能有用,而且這個博客還將記錄我的學習過程。如何在JavaScript對象本身存儲在數組索引中時打印對象的每個單獨屬性?

而不是硬編碼每個新帖子到index.html頁面我想創建一個管理頁面類型有兩個input字段type="text",一個用於標題的帖子和另一個帖子的內容。我的提交按鈕將從我的用戶輸入這些字段,並將它們存儲在一個對象中,該對象是我的構造函數,而每個對象將存儲在一個名爲posts的數組中。

然後我想遍歷數組,並打印出每個帖子的每個對象的單獨屬性......每個屬性是titledate,content。到目前爲止,我可以用這三個屬性創建一個對象並將其存儲在我的數組的零索引(array[0])中,但是當我使用for-loop打印出對象來遍歷數組時,它會打印整個對象。 ..我想我需要訪問我的for循環中的每個屬性?

另外我在這個代碼塊中意識到我打印到控制檯,但我只是這樣做,以確保某些工作正常。在代碼的最後,我發佈了它在控制檯中輸出的內容。現在我只需要分解該對象中的每個屬性並將它們打印到各自的HTML標記中。

我一直在尋找幾天,然後才決定發佈信息,而且找不到任何特定於我正在嘗試使用JavaScript的內容。預先感謝您的幫助。

這裏是我到目前爲止的代碼:

document.getElementById('button').onclick = function() { 
 
    var title = document.getElementById('title').value; 
 
    var content = document.getElementById('content').value; 
 
    var posts = []; 
 
    var makePost = function(title, content) { 
 
    return { 
 
     title: title, 
 
     date: Date(), 
 
     content: content 
 
    } 
 
    } 
 
    posts.unshift(makePost(title, content)); 
 
    for (var i = 0; i < posts.length; i++) { 
 
    var myPost = posts[i]; 
 
    console.log(myPost); 
 
    } 
 
}
* { 
 
    box-sizing: border-box; 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
form { 
 
    position: relative; 
 
    top: 20px; 
 
    left: 20px; 
 
    margin-bottom: 50px; 
 
} 
 
h3 { 
 
    margin: 10px; 
 
} 
 
#title { 
 
    margin: 10px; 
 
} 
 
#date { 
 
    margin: 10px; 
 
} 
 
#content { 
 
    margin: 10px; 
 
}
<h3>Type the content that you would like to show in the post section of the blog</h3> 
 
<form class="form" action="index.html" method="post"> 
 
    Title:<input id="title" type="text" name="name" value="" placeholder="Type title here"><br /> 
 
    <!-- Date:<input id="date" type="text" name="name" value="" placeholder="Type date here"><br /> --> 
 
    Content:<input id="content" type="text" name="name" value="" placeholder="Type content here"> 
 
    <input id="button" type="button" name="name" value="Submit"> 
 
</form> 
 
<h2 id="displaytitle">This is the title of the post</h2> 
 
<h2 id="displaydate">This is the date of the post</h2> 
 
<h2 id="displaycontent">This is the content of the post</h2>

下面是它打印到控制檯:

Object {title: "This is my title", date: "Fri Feb 19 2016 09:54:37 GMT-0800 (PST)", content: "This is my content"} 
+3

你基本上只是問如何['爲... in'](https://developer.mozilla.org/en-US/docs/ Web/JavaScript/Reference/Statements/for ... in)循環工作? – adeneo

回答

0

遍歷您的陣列並打印出你的衆所周知的屬性,使用此:

posts.forEach(function(post) { 
    console.log("Title: " + post.title); 
    console.log("\tDate: " + post.date); 
    console.log("\tContent: " + post.content); 
} 
1
for (var i = 0; i < posts.length; i++) { 
    var myPost = posts[i]; 
    for(var key in myPost) { 
      console.log(myPost[key]); 
    } 
    } 
0
for (var k in target){ 
if (target.hasOwnProperty(k)) { 
    alert("Key is " + k + ", value is" + target[k]); 
} 
} 
相關問題