gpt4 book ai didi

javascript - Uncaught ReferenceError : Cannot access 'stocks' before initialization

转载 作者:行者123 更新时间:2023-12-03 23:06:37 29 4
gpt4 key购买 nike

我正在尝试将一个对象导入另一个 JS 文件,但我不断收到此错误,未捕获的 ReferenceError:在初始化之前无法访问“股票”。我已经申报了库存,并且我已经正确导入了它,所以我看不出我做错了什么。任何帮助深表感谢。谢谢。

在股票文件中:

export const stocks = {
megaCorp: {
name: 'Mega Corporation',
value: decideStockValue(),
portIn: 0,
document: "mega"
},

lunaBake: {
name: "Luna Baking",
value: decideStockValue(),
portIn: 1,
document: "luna"
},
}

在用户文件中:
import { stocks } from "./stocks.js";

export let user = {
money: 2000,
portfolio: [0, 0, 0, 0]
}

function getValue () {
let value = user.money;
let cannon = stocks.cannonRock.value * user.portfolio[0];
let alpha = stocks.alphaComp.value * user.portfolio[1];
let luna = stocks.lunaBake.value * user.portfolio[2];
let mega = stocks.megaCorp.value * user.portfolio[3];
value += cannon;
value += alpha;
value += luna;
value += mega;
return value;
}

user.value = getValue();

最佳答案

再次查看代码,它似乎在语法上很好,所以这不是一个答案,但我宁愿分享一段代码来看看它的行为方式。

您分享的错误 Uncaught ReferenceError: Cannot access 'variable_name' before initialization在初始化之前访问词法变量时会抛出它(所谓的时间死区错误),但是在您共享的代码中没有任何东西应该抛出这个错误。

例如这段代码会抛出这个错误

const x = 3
function a(){
console.log(x)
const x = 5;
}
a()

假设确实错误来自用户文件,那么下面的代码可能会解决它。在代码中,你有 getValue 是一个应该提升的函数表达式(这应该没问题),但可能是你使用的捆绑器行为不端。
import { stocks } from "./stocks.js";

const getValue = (stocks, money, portfolio) => {
let value = money;
let cannon = stocks.cannonRock.value * portfolio[0];
let alpha = stocks.alphaComp.value * portfolio[1];
let luna = stocks.lunaBake.value * portfolio[2];
let mega = stocks.megaCorp.value * portfolio[3];
value += cannon;
value += alpha;
value += luna;
value += mega;
return value;
};

const money = 2000;
const portfolio = [0, 0, 0, 0];
export const user = {
money,
portfolio,
value: getValue(stocks, money, portfolio),
};


关于javascript - Uncaught ReferenceError : Cannot access 'stocks' before initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62202164/

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