小程序API(1.2)利用for循环计算阶乘的方法
<!--pages/index.wxml--> <view class="box"> <view class=\'title\'>阶乘计算器</view> <input type=\'number\' bindinput=\'getInput\' placeholder=\'请输入要求阶乘的数\'></input> <text>结果为:{{result}}</text> </view>
/* pages/index.wxss */ input { border-bottom: 3px solid blue; height: 40px; width: 200px; margin: 20px 0; }
Page({ getInput: function (e) {//bindinput事件引发的函数 this.inputVal = e.detail.value //定义对象属性并把输入框数据赋值给它 }, onShow: function() { //生命周期函数,小程序界面显示时调用 var that = this;//回调函数中需要引用this,但回调函数中引用this容易引起一些错误,所以把this提前赋值给临时定义的变量that that.isShow = true; //定义对象属性并赋值 wx.onAccelerometerChange(function(e) { //调用加速度改变函数 if (!that.isShow) { //判断小程序界面是否显示 return } if (e.x > 0.5 || e.y > 0.5 || e.z > 0.5) { //判断手机晃动是否达到一定程度 wx.showToast({ //显示消息框 title: \'摇一摇成功\', //消息框标题 icon: \'success\', //消息框图标 duration: 2000 //消息框存在的时间 }) var result = 1; for (var i = 1; i <= that.inputVal; i++) { //计算阶乘 result = result * i } that.setData({//result的值渲染到wxml里去 result: result }) } }) }, onHide: function() { //屏幕隐藏时调用 this.isShow = false; }, })
计算阶乘的算法
阶乘的计算公式为