我制作了一个脚本来生成一些虚构的帐户和交易,并且自己运行脚本是可以的。它会按预期生成2个列表,但是我需要在另一个文件中使用这些列表。当我在最后导出变量并将其重新导入另一个文件时,我收到一堆no-undef警告,并且构建失败。
我认为这是因为我的导出对象包含函数。如何强制这些函数只生成值,以便我可以正确导出它们?
randomint = (start, end) => {
let diff = end - start;
return Math.floor(Math.random() * diff) + start
}
chance = (rate=0.5) => {
return Math.random() > rate ? true : false;
}
pad = (n, width, z) => {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
NUM_OF_ACCOUNTS = 10
NUM_OF_TXS = randomint(30, 40)
let accounts = [];
let transactions = [];
for (let i=0; i< NUM_OF_ACCOUNTS; i++) {
accounts.push({
id: i,
ref: `SMAR_A${pad(i, 3)}`,
account: randomint(10000000, 99999999),
sortcode: randomint(100000, 9999999),
fraud: chance(0.1),
balance: Math.round(Math.random() * 85000, 2)
})
}
for (let t = 0; t < NUM_OF_TXS; t++) {
// Lookup a random account number to generate a transaction for
acct_num = randomint(0, accounts.length - 1 )
transactions.push({
ref: accounts[acct_num].ref,
deposit: Math.round(Math.random() * 85000, 2),
account: accounts[acct_num].account,
sortcode: accounts[acct_num].sortcode,
})
};
export accounts;
export transactions;
我尝试了多种进出口,但没有运气。
Line 1: 'randomint' is not defined no-undef
Line 6: 'chance' is not defined no-undef
Line 10: 'pad' is not defined no-undef
Line 16: 'NUM_OF_ACCOUNTS' is not defined no-undef
Line 17: 'NUM_OF_TXS' is not defined no-undef
Line 17: 'randomint' is not defined no-undef
Line 23: 'NUM_OF_ACCOUNTS' is not defined no-undef
Line 26: 'pad' is not defined no-undef
Line 27: 'randomint' is not defined no-undef
Line 28: 'randomint' is not defined no-undef
Line 29: 'chance' is not defined no-undef
Line 34: 'NUM_OF_TXS' is not defined no-undef
Line 35: 'acct_num' is not defined no-undef
Line 35: 'randomint' is not defined no-undef
Line 38: 'acct_num' is not defined no-undef
Line 40: 'acct_num' is not defined no-undef
Line 41: 'acct_num' is not defined no-undef
我在做错什么,我该如何改善出口的运作方式?我想了解自己的错误和错误,以便我可以学习和改进。
答案 0 :(得分:3)
该行为来自javascript严格模式。您的代码在“草率模式”下工作。特别是,您遇到了以下规则(取自严格模式的Mozilla documentation):
严格模式使得不可能意外创建全局 变量。在普通的JavaScript中,迷惑分配中的变量 在全局对象上创建一个新属性,然后继续“工作” (尽管将来可能会失败:很可能在现代JavaScript中)。 分配,这会意外地创建全局变量 在严格模式下引发错误:
在您的代码中,这发生在这里:
randomint = (start, end) => {
let diff = end - start;
return Math.floor(Math.random() * diff) + start
}
以及所有其他不使用const
,let
或var
引入变量的地方。
这是一个简单的解决方法,只需在每个变量前面添加const
或let
:
const randomint = (start, end) => {
let diff = end - start;
return Math.floor(Math.random() * diff) + start
}
const chance = (rate=0.5) => {
return Math.random() > rate ? true : false;
}
// etc
您只会在模块上遇到此问题,因为默认情况下模块启用了严格模式,而普通脚本则没有。
答案 1 :(得分:1)
然后只声明它们。代替
randomint = (start, end) => {
写
const randomint = (start, end) => {
等等。