js数组使用foreach时调用外部变量说未定义

for(let attrIndex in this.attrColum){                      attr.push(this.attrColum[attrIndex].label+":"+this.skuData[item][this.attrColum[attrIndex].prop])
    }

上面是this.attrColum数组遍历的操作,其中要用到外部的另一个数组this.skuData,这代码变成foreach怎么写?其中item是外部另一个循环的序列

this.attrColum.forEach(function(element){
    attr.push(element.lable)+":"+this.skuDate[item][element.prop]
})

按上面的方法,在函数体内this.skuData显示未定义。

阅读 7.9k
3 个回答

箭头函数

this.attrColum.forEach(element=>{
    attr.push(element.lable)+":"+this.skuDate[item][element.prop]
})

不知道你外部是怎么写的,应该this指向问题吧forEach用箭头函数

箭头函数是可以的,forEach外部重新申明一下也是可以的let self=this attr.push(element.lable)+":"+self.skuDateitem

推荐问题