gpt4 book ai didi

Javascript fetch 和 console.log json 给出未定义

转载 作者:行者123 更新时间:2023-12-01 01:54:39 26 4
gpt4 key购买 nike

html 正文::

<button class="getUsers">get users</button>

JS::

const getUsers = () = > {
fetch("users.json")
.then((res) = > {
res.json()
})
.then((data) = > {
console.log(data);
})
}
document.querySelector(".getUsers").addEventListener("click", getUsers)

用户.json::

[{
"id": 1,
"name": "Rick",
"email": "rick@gmail.com"
}, {
"id": 2,
"name": "maria",
"email": "maria@gmail.com"
}, {
"id": 3,
"name": "gadnjaman",
"email": "gadnjaman@gmail.com"
}]

我的问题是为什么单击按钮时会出现未定义以及如何修复它?

最佳答案

Arrow functions MDN web doc 中所述:

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.

所以,正如评论中所说,要么( block 体):

.then((res) = > {
return res.json()
})

或(简洁正文):

.then(res => res.json())

关于Javascript fetch 和 console.log json 给出未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com