【问题标题】:Array has values in it, but not able to access them, what might be the problem?数组中有值,但无法访问它们,可能是什么问题?
【发布时间】:2019-09-09 08:56:31
【问题描述】:

我通过回调函数得到两个值(字符串),假设这两个值是 a 和 b,所以现在我将把这些值推送到数组中。当我 console.log 这个数组时,只有当我通过单击箭头符号展开数组时才会显示这些值。当我尝试访问索引值时,它显示未定义。所以我猜有一个问题函数调用?

funcOuter() {
    let newList =[];
    this.calledFunc(function (param) {
        newList.push(param);
    });
    console.log(newList[1]);
}

实际输出:

未定义

预期输出:

123.234.556

【问题讨论】:

  • 好的..当然。请告诉我问题的哪一部分不明白。我会尽快更改。
  • 你传入的参数值是多少?
  • 你可能在那里有一个异步调用,当你做 console.log 时答案还没有准备好
  • @Vega 哦.. 是的,这可能是问题所在。

标签: javascript angular typescript


【解决方案1】:

最好是可视化代码执行:

堆栈S

H

队列Q

在执行时,您的 funcOuter 将被置于 S

赋值、函数调用和日志也是如此:

SfuncOuterlet newList =[];

分配被执行...

SfuncOuterthis.calledFunc(callback);

函数被执行...

SfuncOuterthis.calledFunc(callback);calledFunc inner block

内部块和异步完成

SfuncOuterconsole.log(newList[1])

possible async calls

日志完成:

SfuncOuter,

possible async calls

外部完成:

S

possible async calls

堆栈从 Q 中填充:

Scallback,

possibly more async calls

push 被执行:

Scallbackpush

等等;) Event Loop

所以把你的代码改成:

funcOuter() {
    let newList =[];
    this.calledFunc(function (param) {
        newList.push(param);
        newList[1] && console.log(newList[1]);
    });

}

应该给出预期的结果。

【讨论】:

    【解决方案2】:

    如果你使用angular 2+,为什么有回调函数,我认为这是一个解决方案。

    export class AchievementComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
      }
    
      async funcOuter() {
        let newList =[];
        const param = await this.funcInner();
        newList.push(param);
      }
    
      funInner() {
        return new Promise((resolve, reject)=>{
          this.calledFunc((param)=>{
             resolve(param);
          })
        })
      }
    
    }
    

    【讨论】:

    • 好的..我认为这也可以,因为它会等待被调用的函数得到它的参数。但我得到了解决方案。不管怎样,谢谢你给我宝贵的时间!!
    • 不客气,我想如果你使用箭头函数,你不需要声明 var that = this
    猜你喜欢
    • 2014-10-22
    • 1970-01-01
    • 2019-07-20
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多