javascript - 在 javascript forEach 函数中访问“this”
问题描述
我有一个特殊的场景,我想从“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 方式是什么?我经常遇到这种情况,我总是觉得我想出了粗略的解决方案,或者至少可以做一些更容易的事情。对此的任何帮助都会很棒。
解决方案
许多内置插件,包括 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开始支持
推荐阅读
- javascript - 为什么 Node 不作为 Express 的依赖项包含在内?
- python-3.x - Pyautogui鼠标点击不同的分辨率
- javascript - Monaco 编辑器中的选项卡
- angular - AngularMaterial 对话框未正确打开
- javascript - 如何将对象合并为一个字符串
- java - 在 Selenium 中执行操作时如何查看鼠标指针?
- python - 关键错误:具有编辑距离的 Python 中为 0
- javascript - 检查对象是否包含在另一个对象中
- python - 如何确保函数将我写的内容变成字符串
- javascript - 用于禁用 window.onbeforeunload 的用户脚本