【问题标题】:Variable with assigned value is still undefined when checked with typeof [duplicate]使用 typeof 检查时,具有赋值的变量仍然未定义 [重复]
【发布时间】:2020-06-18 17:44:26
【问题描述】:
我正在为一个网站做一个简单的汇率按钮,我正在用一个变量下的设定值对其进行测试。我仍然遇到错误,因为当我检查这个变量时它显示为未定义。可能是什么原因?我知道这是基本的东西,但我看不出这里可能是什么问题。感谢您帮助解决这个问题!
组件.ts:
public price: number = 500;
public exchangeUsd;
public priceUsd;
countUsd() {
fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
.then((resp) => resp.json())
.then(function(data) {
let exchangeUsd = data.rates[0].mid
console.log("Exchange rate: " + exchangeUsd)
console.log(this.price) //here the typeof shows undefined
priceUsd = exchangeUsd * this.price //and it also makes this simple multiplication impossible
})
}
Stackblitz:https://stackblitz.com/edit/flight-date-picker-with-service-done
【问题讨论】:
标签:
javascript
angular
fetch
undefined
typeof
【解决方案1】:
无法测试,但主要是因为.then(function(data)。用箭头函数替换它
.then((data) => {
let exchangeUsd = data.rates[0].mid
}
【解决方案2】:
这是一个范围问题。你有两个选择。或者您在then(...) 中使用箭头函数,或者通过使用变量捕获它来将作用域传递给函数:
选项 1:箭头函数
function countUsd() {
fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
.then((resp) => resp.json())
.then((data) => {
let exchangeUsd = data.rates[0].mid
console.log("Exchange rate: " + exchangeUsd)
console.log(price) //here the typeof shows undefined
priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
})
}
选项 2:使用变量捕获范围
function countUsd() {
const classScope = this;
fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
.then((resp) => resp.json())
.then(function(data) {
let exchangeUsd = data.rates[0].mid
console.log("Exchange rate: " + exchangeUsd)
console.log(classScope.price) //here the typeof shows undefined
priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
})
}
【解决方案3】:
你在 console.log 中有 this.price 应该是 price。
下面的代码对你有用:
public price: number = 500;
public exchangeUsd;
public priceUsd;
function countUsd() {
fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
.then((resp) => resp.json())
.then(function(data) {
let exchangeUsd = data.rates[0].mid
console.log("Exchange rate: " + exchangeUsd)
console.log(price) //here the typeof shows undefined
priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
})
}