我正在將一個陣列匯入一個模塊,并從該陣列中添加和洗掉專案。當我推送時,它會將專案全域添加到陣列中,以至于如果我在另一個模塊中使用相同的陣列,它將包含我推送的這個專案。但是當我嘗試過濾時,同一個陣列使用過濾器,它只會在該特定模塊中洗掉。我怎樣才能讓它全域修改?
let { ignore } = require('../utils/handleIgnore');
const questions = require('./quesiton');
const AgendarCollector = async (client, message) => {
ignore.push(message.from);
let counter = 0;
const filter = (m) => m.from === message.from;
const collector = client.createMessageCollector(message.from, filter, {
max: 4,
time: 1000 * 60,
});
await client.sendText(message.from, questions[counter ]);
collector.on('start', () => {});
await collector.on('collect', async (m) => {
if (m) {
if (counter < questions.length) {
await client.sendText(message.from, questions[counter ]);
}
}
});
await collector.on('end', async (all) => {
ignore = ignore.filter((ignored) => ignored !== message.from);
console.log(ignore);
const finished = [];
if (all.size < questions) {
console.log('n?o terminado');
}
await all.forEach((one) => finished.push(` ${one.content}`));
await client.sendText(message.from, `${finished}.\nConfirma?`);
});
};
module.exports = AgendarCollector;
看,在這段代碼中,匯入忽略陣列,然后在代碼開始時將專案推送到然后在代碼結束時洗掉。但是當我在另一個模塊中檢查相同的陣列時,該專案會繼續。我試圖通過使用此模塊中的函式來更改此陣列忽略但仍然無法正常作業
let ignore = [];
const addIgnore = (message) => {
ignore.push(message.from);
};
const removeIgnore = (message) => {
ignore = ignore.filter((ignored) => ignored !== message.from);
console.log(ignore);
};
console.log(ignore);
module.exports = { ignore, addIgnore, removeIgnore };
uj5u.com熱心網友回復:
您正在使用變數進行匯入和匯出,因此遇到了問題。
相反,請使用吸氣劑。
撰寫一個回傳陣列的函式ignore
。像這樣的東西:
const getIgnoredList = () => {
return ignore;
};
并在您的第一個代碼中,匯入getIgnoredList
并替換ignore
為getIgnoredList()
解釋 :
每當我們匯入變數時,只會匯入該特定時間的值,并且不會有任何資料系結。因此,即使您認為您正在更新實際資料,資料也不會發生任何變化。
希望這對你有幫助!!如果您遇到任何錯誤或堅持上述錯誤,請發表評論。
uj5u.com熱心網友回復:
當您使用 require(...) 陳述句時,它只執行一次。因此,當您嘗試訪問該屬性時,它每次都會給出相同的值。相反,您應該使用吸氣劑
let data = {
ignore : [],
get getIgnore() {
return this.ignore
}
}
module.export = {
getIgnore: data.getIgnore,
}
ignore
然后無論你想訪問哪里
var {getIgnore}= require('FILE_NAME')
現在:console.log(getIgnore)
將呼叫 getter 并為您提供當前值ignore
使用 getter 將允許您從其他模塊訪問特定變數,但是如果您想從其他模塊更改這些變數的值,則必須使用 setter。
更多關于 getter的資訊在這里
更多關于二傳手的資訊在這里
uj5u.com熱心網友回復:
作業!我寫了這個并且作業得很好。伙計們
let ignore = [];
const getIgnore = (order, message) => {
switch (order) {
case 'add':
ignore.push(message.from);
return ignore;
case 'remove':
ignore = ignore.filter((ignored) => ignored !== message.from);
return ignore;
default:
return ignore;
}
};
module.exports = { getIgnore };
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504609.html
標籤:javascript 节点.js 模块
下一篇:設計模式之解釋器模式