wumi_blog icon indicating copy to clipboard operation
wumi_blog copied to clipboard

获取数组中的某一项

Open 5Mi opened this issue 8 years ago • 0 comments

  • 获取数组中的某一项

    之前在vuex的mutate中经常会写类似这种function

    //
      SOME_MUTATE(state,nowobj){
          for(let obj of state.objlist){
              //在数组中找到当前的项
              if(Object.is(nowproduct,obj)){
                  //someoperation
              }
          }
      }
    

    之后想到array.indexOf();

    //
      SOME_MUTATE(state,nowobj){
          let index = state.objlist.indexOf(nowobj);
          //在数组中找到当前的项
          state.objlist[index]
      }
    

    其实在templete中循环渲染时 是可以带出 数组的index的通过使用$index 那么上面的函数则完全可以将nowobj参数替换为index改写成:

    SOME_MUTATE(state,index){
        //在数组中找到当前的项
        state.objlist[index]
    }
    

    当然以上都是可以取到index的情况(或某一项来获得index),如果只通过某一项的id来获取这一项,还是要通过循环的方式,比如:

      let id = getUrlParam("id");
          for (let item of this.products){
              if(item.id == id){
                  return item;
              }
          }
    
    • 伪元素 :after等不是dom元素无法绑定事件(随手一记)

5Mi avatar Jun 12 '16 13:06 5Mi