每次单击都会将对象中的一些数据添加到 div

Each click add some data from object to div

我有一个按钮,div 在 HTML 中是空的。

<button id="add_sentence">Click here!</button>
<div id="parent"></div>

在 JS 中,我在数组中有数据

let data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn front-end development}]

我需要一个函数,当我点击按钮 ("#add_sentence") 时,它只需要从数组 ("data") 中提取一个句子并添加到 div ("#parent ").

我只需单击 1 次即可将所有数组添加到空 div。但我想要第一次点击添加第一句话。然后,第二次点击添加第二句。第 3 次点击添加第 3 句,依此类推。

有人能帮忙吗?

let data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn fron-end development"}];

const button = document.querySelector("#add_sentence");
const parent = document.querySelector("#parent");

let clickCount = 0;

button.addEventListener('click', () => {
  if (clickCount < data.length) {
    const nextSentence = document.createElement('p');
    nextSentence.innerText = data[clickCount].sentence;
    parent.appendChild(nextSentence);
    clickCount++;
  }
})
<button id="add_sentence">Click here!</button>
<div id="parent"></div>

没有点击次数...

var data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn front-end development"}],
    prnt = document.getElementById("parent"),
    bttn = document.getElementById("add_sentence");

bttn.addEventListener("click", _ => data.length && (prnt.textContent += `${data.shift().sentence}
`));
#parent { white-space: pre;
}
<button id="add_sentence">Click here!</button>
<div id="parent"></div>