箭头函数表达式的语法比函数表达式更简洁,并且没有自己的this,arguments,super或new.target。箭头函数表达式更适用于那些本来需要匿名函数的地方,并且它不能用作构造函数。 (param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression //相当于:(param1, param2, …, paramN) =>{ return expression; } // 当只有一个参数时,圆括号是可选的: (singleParam) => { statements } singleParam => { statements } // 没有参数的函数应该写成一对圆括号。 () => { statements }
例1 const materials = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium' ]; //array.findIndex(function(currentValue, index, arr), thisValue) //findIndex方法 //参数 描述 //currentValue 必需。当前元素 //index 可选。当前元素的索引 //arr 可选。当前元素所属的数组对象 //thisValue 可选。 传递给函数的值一般用 "this" 值。 //如果这个参数为空, "undefined" 会传递给 "this" 值 console.log(materials.finndIndex(element => element .length>8)); // 3然而 ,基础函数表达式function(value){ return value} 与箭头函数 (param1, param2, …, paramN) => { statements } 使用的频率都不尽相同,一直用也没怎么留意 但是 ,最近留意到一个bug 当你的函数表达式为 (param1, param2, …, paramN) => expression 的效果与 (param1, param2, …, paramN) => { statements }并不一致
addshop() { const listitem = { id: this.goodslist.id, count: this.$store.state.value, price: this.goodslist.sell_price }; const list = JSON.parse(window.localStorage.getItem("shop")); if (list == null) { this.local.push(listitem); window.localStorage.setItem("shop", JSON.stringify(this.local)); return false } /*console.log(list)* 此处标记A 后文引用/ //此处 我是用的是基础函数表达式 const n = list.findIndex(function(x){return x.id===listitem.id} ); //此处 我是用的是箭头函数表达式1 const m = list.findIndex((x)=>{return x.id===listitem.id} ); //此处 我是用的是箭头函数表达式2 const c = list.findIndex(x=> x.id===listitem.id); //此处 我是用的是箭头函数表达式3 const t = list.findIndex((x)=> x.id===listitem.id); //此处 我是用的错误函数表达式1 // const error = list.findIndex((x)=> {x.id===listitem.id}); // const error = list.findIndex(x=> {x.id===listitem.id}); console.log(n,'----',m,'-----',c,'-----',t'-----',error); if (n == -1) { list.push(listitem); } else { list[n].count+=listitem.count } window.localStorage.setItem("shop", JSON.stringify(list)); this.toast.success("添加成功"); }此段函数,应用场景为购物车加购商品
加购商品时 会有商品独有id,商品数量,商品价格 以对象数据存储
以防刷新,数据丢失情况,存放于localStorage 以放后续数据更迭
分情况考虑 ,当第一次加过商品时,需创建localStorage,当第n次加购商品时,需要往localStorage增加对象数据
当第n次加购中,加购的商品,在之前加购过,那么localStorage不能存在两次加购数据,那么需要进行处理
我的处理方式为,使用数组findIndex方法 判断localStorage的数据是加购过我目前要加购的商品 ,可用商品id判断(id真是一个好东西),如果以前没加购过,那么直接可以向localStorage推送数据;否则,找到那个商品,支队该数据进行数量编辑,最后将更新后的数据推送localStorage即可
最后, 说明下我的错误情况 ,当我一不正规书写箭头函数时,findIdex也会执行 但是得到的索引结果为error=-1;而且A的结果是我后面别push后的list数据,似乎没有按照预编译格式执行。