为了账号安全,请及时绑定邮箱和手机立即绑定

在 javascript forEach 函数中访问“this”

在 javascript forEach 函数中访问“this”

慕妹3146593 2022-09-02 16:59:22
我有一个特殊的场景,我想从“this”访问数据,同时查看一个数组,该数组也在我的Vue组件上定义。例: data () {    return {      question: [],      inputList: [],      form: {}    }  }, methods: {   onSubmit: function () {     let predictionParams = {}     this.inputList.forEach(function (element) {       predictionParams[element.detail] = this.form[element.detail]     })   }错误:this.form is not defined in the context of the forEach loop问题:JS处理此类案件的惯用方式是什么?我经常遇到这种情况,我总是觉得我想出了粗略的解决方案,或者至少可以做一些更容易的事情。对此的任何帮助都会很棒。
查看完整描述

3 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

许多内置组件(包括 forEach)都包含一个可选的“this”活页夹:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

利用这一点来发挥你的优势:

this.inputList.forEach(function (element) {
   predictionParams[element.detail] = this.form[element.detail]
},this)

自 ie9 起受支持


查看完整回答
反对 回复 2022-09-02
?
炎炎设计

TA贡献1808条经验 获得超4个赞

arrow 函数语法避免了重新绑定此

 this.inputList.forEach(element => {
   predictionParams[element.detail] = this.form[element.detail]
 })


查看完整回答
反对 回复 2022-09-02
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

您可以使用箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 它将它绑定到函数中


 data () {

    return {

      question: [],

      inputList: [],

      form: {}

    }

  },

 methods: {

   onSubmit: () => {

     let predictionParams = {}


     this.inputList.forEach((element) => {

       predictionParams[element.detail] = this.form[element.detail]

     })

   }


查看完整回答
反对 回复 2022-09-02
  • 3 回答
  • 0 关注
  • 328 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号