所以我對(duì) JavaScript 還很陌生,我有一個(gè)充滿(mǎn)名詞的文本文檔,并認(rèn)為用這些名詞創(chuàng)建 api 的好方法。我閱讀了文件并將它們添加到列表中public List<Noun> getData() throws IOException { Scanner sc = new Scanner(new File("C:\\Users\\Admin\\Desktop\\nounlist.txt")); List<Noun> nouns = new ArrayList(); while (sc.hasNextLine()) { nouns.add(new Noun(sc.nextLine())); } return nouns;}這個(gè)列表我用 Gson 轉(zhuǎn)換為 Json:@GET@Path("/nouns/amount=all")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public Response getAllNouns() throws IOException { return Response.ok().entity(gson.toJson(nf.getData())).build();}然后我開(kāi)始用 js 創(chuàng)建我的前端并嘗試獲取數(shù)據(jù),但遇到了一個(gè)問(wèn)題,說(shuō) uncaught in promise, type error, nouns.forEach is not a functionimport "bootstrap/dist/css/bootstrap.css";const root = document.getElementById("root");var url = "http://localhost:8084/CORSJavaJax-rs/api/noun/nouns/amount=all";var tbody = document.getElementById("tbody");var btn = document.getElementById("btnsend");// fetch(url)// .then(res => res.json)// .then(nouns => {// var n = nouns.map(noun => {// return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";// });// tbody.innerHTML = n.join("");// });btn.addEventListener("click", function() { fetch(url) .then(res => res.json) .then(nouns => { console.log(nouns); var n = nouns.forEach(noun => { return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>"; }); tbody.innerHTML = n.join(""); });});我嘗試了 map 和 forEach 但沒(méi)有成功,也許我錯(cuò)過(guò)了一些東西,或者有些東西我只是不明白為什么我不能映射數(shù)據(jù)。
1 回答

胡說(shuō)叔叔
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
對(duì)于您想要的,正確的用法是map調(diào)用,而不是forEach. ForEach 不返回值,它只是在集合上迭代。
您收到is not a function錯(cuò)誤的原因很可能是由于缺少對(duì)res.json. 應(yīng)該是res.json()。
btn.addEventListener("click", function() {
fetch(url)
.then(res => res.json())
.then(nouns => {
console.log(nouns);
var n = nouns.map(noun => {
return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
});
tbody.innerHTML = n.join("");
});
});
添加回答
舉報(bào)
0/150
提交
取消