我在函式中有一個變數,我想在函式之外呼叫它,但是它顯示“名稱未定義”。請告知我如何使這個變數成為全域變數。
n = Math.ceil(Math.random() * 80);
console.log(n)
function randomStarwars(){
fetch('https://swapi.dev/api/people/' n)
.then(response => response.json())
.then(data=> {
var Name = data.name
})
}
addEventListener("click", randomStarwars)
console.log(Name)
uj5u.com熱心網友回復:
您可能想看看變數范圍。
您無法訪問它的原因是因為它是在.then()lambda 函式中定義的,并且只能在那里訪問。
要讓它在該函式之外可用,您需要在它之外宣告它:
n = Math.ceil(Math.random() * 80);
var Name = ""; // Here, for example
console.log(n)
function randomStarwars(){
fetch('https://swapi.dev/api/people/' n)
.then(response => response.json())
.then(data=> {
Name = data.name; // Remove 'var', because it's already declared
})
}
addEventListener("click", randomStarwars)
console.log(Name)
評論后更新:
您看不到您的值,因為該值是在Promiseconsole.log中分配的,在宣告時永遠不會正確運行。
為了有效console.log地Name,您需要鏈接另一個.then()并將其記錄在那里:
n = Math.ceil(Math.random() * 80);
var Name = ""; // Here, for example
console.log(n)
function randomStarwars(){
fetch('https://swapi.dev/api/people/' n)
.then(response => response.json())
.then(data=> {
Name = data.name; // Remove 'var', because it's already declared
})
.then(() => {
console.log(Name) // This guarantees the value has been set, aside from any errors that might occur before
})
}
addEventListener("click", randomStarwars)
console.log(Name) // This is executed before the Name is set
uj5u.com熱心網友回復:
您必須在 fetch 函式之前宣告變數
var Name = "";
n = Math.ceil(Math.random() * 80);
console.log(n)
function randomStarwars(){
fetch('https://swapi.dev/api/people/' n)
.then(response => response.json())
.then(data=> {
Name = data.name
})
}
addEventListener("click", randomStarwars)
console.log(Name)
uj5u.com熱心網友回復:
在函式之外定義變數:
var global_Name; // this is your global variable
n = Math.ceil(Math.random() * 80);
console.log(n)
function randomStarwars(){
fetch('https://swapi.dev/api/people/' n)
.then(response => response.json())
.then(data=> {
global_Name= data.name // use it without var
})
}
addEventListener("click", randomStarwars)
console.log(Name)
function2()
{
global_Name = // use it without var
}
function3()
{
global_Name = // use it without var
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472638.html
標籤:javascript
