孫 鵬 張文靜
(沈陽工學(xué)院信息與控制學(xué)院,遼寧 撫順 113122)
小程序背單詞開發(fā)一共分為3個(gè)部分:數(shù)據(jù)隨機(jī)獲取,輸入監(jiān)視與字符匹配,提示按鈕功能實(shí)現(xiàn),首先需要前端獲取到云端數(shù)據(jù)庫內(nèi)的數(shù)據(jù),再通過輸入監(jiān)視與數(shù)據(jù)庫內(nèi)數(shù)據(jù)進(jìn)行匹配,得到單詞拼寫的結(jié)果,在同學(xué)不知道單詞的情況可以點(diǎn)擊提示按鈕查看正確單詞拼寫,達(dá)到背單詞的目的。
在云數(shù)據(jù)庫內(nèi)獲取數(shù)據(jù)時(shí)需要重新調(diào)用數(shù)據(jù)庫并使用隨機(jī)函數(shù)sample()當(dāng)作索取的條件來隨機(jī)取出詞匯,并將取出的數(shù)據(jù)賦值給為全局變量,使輸入內(nèi)容運(yùn)用KMP算法的逆運(yùn)算邏輯對(duì)其字符匹配,并當(dāng)用戶不認(rèn)識(shí)且不會(huì)拼寫的情況添加提示按鈕提示,達(dá)到背單詞的目的。具體代碼如下:
數(shù)據(jù)庫獲取數(shù)據(jù);
調(diào)用數(shù)據(jù)庫;
const cloud = wx.require(‘wx-server-sdk’),
cloud.init(),
const db = wx.cloud.database(),
db.collection(‘SITdatabase’)
.aggregate()
.sample({size: 1, })
.end()
.then(res => {this.setData({list: res.list})
console.log(res)
let words = res.list[0].English
app.globalData.words = words})
代碼解釋:首先獲取數(shù)據(jù)庫,再進(jìn)行對(duì)數(shù)據(jù)初始化,再隨機(jī)獲取一條數(shù)據(jù),刷新單詞數(shù)據(jù),并打印至控制臺(tái),將已獲取的數(shù)據(jù)作為全局變量app.globalData.words傳到輸入函數(shù)內(nèi)。
將獲取已知的單詞賦值給全局變量app.globalData.words并將其與輸入后的單詞進(jìn)行匹配,并檢查與提示輸入單詞是否正確。具體代碼如下。
inputWordRandom: function (e) {
var word = this.data.word
if (e.detail.value == app.globalData.words) {wx.showToast({title: '回答對(duì)了呢!',
icon: 'success'})
this.setData({color: 'rgb(40, 247, 33)'
if (e.detail.value.length == app.globalData.words.length) {
if (e.detail.value != app.globalData.words) {
wx.showToast({
title: '不對(duì)呀,看看正確答案~',
icon: 'none'})
this.setData({word: app.globalData.words,
color: 'rgb(247, 33, 33)'})}}
console.log(e)},
代碼解釋:先定義data內(nèi)word值作為監(jiān)視對(duì)象,將輸入值與全局變量app.globalData.words進(jìn)行字符匹配,并提示輸入是否正確并刷新字體顏色(this.data.colors)并將輸入內(nèi)容打印至控制臺(tái)。
在同學(xué)們遇到不認(rèn)識(shí)的單詞拼寫時(shí),在此加入了提示功能,為此方便同學(xué)們對(duì)單詞的記憶,具體代碼如下:
getWord: function(e){
if(app.globalData.words ===undefined){app.globalData.words = '點(diǎn)擊查看以查看單詞拼寫' }
wx.showToast({
title: app.globalData.words,
icon: 'none'})},
代碼解釋:當(dāng)同學(xué)點(diǎn)擊提示按鈕的時(shí)候,刷新單詞數(shù)據(jù),并將答案?jìng)鹘oapp.globalData.words作為提示對(duì)象,顯示出單詞答案。
背單詞功能在邏輯上主要運(yùn)用KMP算法的逆運(yùn)算過程,并使用app.globalData.words作為全局變量與輸入值匹配,使得背單詞功能更全面,使用戶背誦單詞的效率更高。