微信小程序之条件判断

前文:

  今天踩了一下午的坑,但是确实很简单的问题。

   我说一下需求:扫描商品的二维码,从而判断,同一个二维码不可多次扫描;

   

 

 点击扫一扫 会在灰色区域展示 扫描的商品信息,比如商品名称,商品码等,但是我们的需求是一物一码,即使是同一个商品也是不同的商品码。

 错误示例:

     最开始我的想法是做判断,因为我会在相对应的js文件中定义一个 productList:[ ],数组来存放数据,

Pages({
    productList: [用来存放,通过后台接口得到的相关商品的数据信息]
    
})

由于我们是一物一码,那唯一的判断条件就是商品码了

wzy.post("/wx/open/getProdcutNameByCode", product, true)
             .then((res) => {
               
               let products={
                 name: res.data.data,
                 code:product.code,
               }

               let productLength = this.data.productIist.length;

              
              //如果列表没有直接推,如果有循环,如果
               if (productLength==0){
                 this.data.productIist.push(products);
                 this.setData({
                   productIist: this.data.productIist
                 })
               }else{

                 for (let i = 0; i < productLength;i++){
                   if (products.code == this.data.productIist[i].code){
                      global.jv.showPop('提示','同一商品不可重复扫描')
                      return
                    }
                 }
                 this.data.productIist.push(products);
                 this.setData({
                   productIist: this.data.productIist
                 })
               }
             }).catch((res) => {
               console.log(res)
               wzy.showPop('提示', '当前网络繁忙,请重新扫描')
             })
         },

原来的思路是:

 

 .then((res) => {
               
               let products={
                 name: res.data.data,
                 code:product.code,
               }

               let productLength = this.data.productIist.length;

              
              //如果列表没有直接推,如果有循环,如果
               if (productLength==0){
                 this.data.productIist.push(products);
                 this.setData({
                   productIist: this.data.productIist
                 })
               }else{
                 // 原来思路:把数组中的每一项code取出来与扫码得到的code进行对比,如果不相等就push到数组中 从而在页面循环,但是发现
 // 当数组的length>1的情况下,会发生即使你扫码得到的code不与原数组相同但是会重复多次,次数由productIist.length决定
                 
            productIist.forEach(item=>{
                   if(item.code !==this.data.productIist.code ) {
                    this.data.productIist.push(products);
                 this.setData({
                   productIist: this.data.productIist
                 })
        }
    
})
             }).catch((res) => {
               console.log(res)
               wzy.showPop('提示', '当前网络繁忙,请重新扫描')
             })
         },              

所以 在上面的正确的示例中 使用for循环 并把判断也写进for循环中  如果数组中的code与扫描的code相等 就会弹出提示框,并且不会执行下面代码,但是当条件不相符的时候,便可以愉快的执行下面的代码了。

文中的wzy封装的方法

posted @ 2018-01-16 19:01  简直走别拐弯  阅读(9481)  评论(0编辑  收藏  举报