I'm Sham
一个在通往码农道路上走走停停的行政文员

小程序制作笔记-js在数组中模糊查找indexOf()

这几天做了1个不用后端直接写在数据中的商品展示demo,因为以前都是直接通过传值给后端来进行搜索获取相应数据的,但是不用后端时,就需要直接在固定的json数组中获取相应数据,这里可以用过js中的indexOf()来实现,下面是代码,只提供.js部分的

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //这里使用的静态写死的商品数据,如启用后端,改成  page: 0, goods: [],
    goods: [
      { "id": "6", "goodsname": "伊利纯牛奶", "goodsdesc": "伊利纯牛奶", "goodsunit": "箱", "goodsprice": "40", "goodsstatus": "onsale", "goodsremark": "", "inventory": "100", "soldnums": "7", "remain": 93, "subtime": "2020-03-27" },
      { "id": "5", "goodsname": "时令当季水果套装", "goodsdesc": "时令当季水果套装", "goodsunit": "份", "goodsprice": "50", "goodsstatus": "onsale","inventory": "100", "soldnums": "8", "remain": 92, "subtime": "2020-03-27" },
      { "id": "4", "goodsname": "自制卤味", "goodsdesc": "自制卤味", "goodsunit": "份", "goodsprice": "40", "goodsstatus": "onsale", "goodsremark": "", "inventory": "100", "soldnums": "8", "remain": 92, "subtime": "2020-03-27" },
      { "id": "3", "goodsname": "老干妈鸡油辣椒酱", "goodsdesc": "老干妈鸡油辣椒酱", "goodsunit": "瓶", "goodsprice": "10", "goodsstatus": "onsale", "goodsremark": "", "inventory": "100", "soldnums": "9", "remain": 91, "subtime": "2020-03-27" },
      { "id": "2", "goodsname": "金龙鱼大豆油", "goodsdesc": "金龙鱼大豆油", "goodsunit": "桶", "goodsprice": "40", "goodsstatus": "onsale", "goodsremark": "", "inventory": "100", "soldnums": "6", "remain": 94, "subtime": "2020-03-27" },
      { "id": "1", "goodsname": "福临门大米", "goodsdesc": "福临门五常大米", "goodsunit": "袋", "goodsprice": "100", "goodsstatus": "onsale", "goodsremark": "", "inventory": "100", "soldnums": "0", "remain": 100, "subtime": "2020-03-27" }
    ],
  },
  onShow: function () {
    var that = this;
    var goods = wx.getStorageSync('goods');  //将goods数据写入缓存
    that.setData({
      goods: goods,
    })
  },
  seachme(e){
    var seachname = e.detail.value.seachname;  //获取搜索框数据
    var goods = wx.getStorageSync('goods');		//从缓存中获取goods数据
    var newgoods = [];		//新建一个新的商品数组
    for (var i=0;i<goods.length;i++){		//循环
      if (goods[i].goodsname.indexOf(seachname)>=0){			//模糊查询搜索框数据在goods数组中对应字符串中位置,如果有,则会大于或者等于0,如没有,则小于0
        newgoods.push(goods[i])
      }
      console.log(newgoods)
	}
    var that = this;
    that.setData({
      goods: newgoods		//将新的goods数组赋值回goods数组重新渲染
    })
    
  },
  
  reset(e){
    var goods = wx.getStorageSync('goods');
    var that = this;
    that.setData({
      goods: goods
    })
  },
})

这样就能实现简单的json数组模糊查询功能啦!

赞(1) 赏杯咖啡!
未经允许不得转载:Sham@双目瞿 » 小程序制作笔记-js在数组中模糊查找indexOf()

评论 抢沙发

评论前必须登录!

 

如果你觉得文章好,请赏1杯速溶咖啡给Sham吧!

微信扫一扫打赏