首页 > 解决方案 > 为什么 eval() 函数会产生未定义的属性?

问题描述

我正在尝试获取对象数组中的属性值,该数组是对象的属性-> this.form.data.output[0].output_total。数组名称、索引和属性名称作为参数传递并分配给变量。

我尝试过使用eval(),并尝试登录到控制台,但结果是Cannot read property data of undefined

这是我调用该函数的方式: (keyup)="form.onNumberChanges($event, 'output', 0, 'output_total')"

这是代码:

onNumberChanges: (event, params, index = null, properties = null) => {
  if (index !== null) {
    console.log(`this.form.data.${params}[${index}].${properties}`);
    /* I am checking if the string isn't proper, but its result as same as I expected --> this.data.output[0].output_total */

    console.log(eval(`this.form.data.${params}[${index}].${properties}`));
    /* resulting cannot read property data of undefined */
  }

我希望我能得到其中的值(0/2/3/或任何其他数字)。有什么线索吗?

标签: javascriptangular

解决方案


尝试将函数更改为下面,因为它看起来像与上下文(this)相关的问题,因为表单未定义

onNumberChanges(event, params, index = null, properties = null) {

并转换为

console.log(this.form.data[params][index][properties])

推荐阅读