Javascript 函数无法正确完成其任务
我有一个问题,因为我不明白为什么我的函数不能给出正确的结果 我有一个主函数Javascript 函数无法正确完成其任务,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我有一个问题,因为我不明白为什么我的函数不能给出正确的结果 我有一个主函数stopClick(),其中我启动了另外两个函数,它们类似,但我传递了两个不同的数组并创建了两个不同的数组: this.timestackCheckDestro(this.props.arraytimestamptamdestro)给我temporaleedestro this.timestackCheckDestro(this.props.arraytimestamptamDestro)给我temporaleResist
stopClick()
,其中我启动了另外两个函数,它们类似,但我传递了两个不同的数组并创建了两个不同的数组:
this.timestackCheckDestro(this.props.arraytimestamptamdestro)
给我temporaleedestro
this.timestackCheckDestro(this.props.arraytimestamptamDestro)
给我temporaleResistro
从获得的结果中,我注意到首先启动的函数能够填充数组到某个点,然后用NaN值填充它。相反,第二个数组要么仅由NaN组成,要么初始位置为NaN,最终位置由值填充
我的代码是:
async stopClick(){
//Code...
await this.timestampCheckDestro(this.props.arrayTimestampDestro);
await this.timestampCheckSinistro(this.props.arrayTimestampSinistro);
//Actions to another function. (after I have the array populated from the two functions)
}
async timestampCheckDestro( timestampDestro ){
//declare variable
for( let i = 0; i < timestampDestro.length; i++){
diffDestro = (( baseDestro + timestampDestro[i] ) - this.contatoreDestro )
this.tempoRealeDestro.push(diffDestro)
}
}
async timestampCheckSinistro( timestampSinistro ){
//declare variable
for( let i = 0; i < timestampSinistro.length; i++){
diffSinistro = (( baseSinistro + timestampSinistro[i] ) - this.contatoreSinistro )
this.tempoRealeSinistro.push(diffSinistro)
}
}
基本上,您在不需要的地方使用了async/await—没有任何Asynchronous和承诺—您的问题是在这个.props.arrayTimestamp*中对daya的处理不当,而不管其他属性是什么(this.contatero*)
async/await
只是为了更容易地处理承诺。您的代码不是异步的,而是线性的。所以根本不需要async/await
。好的,事实上,我得到的结果与我不使用它们时相同。但是您认为我可以如何实现这一点呢?为什么不将console.log放在for循环中,并找出NaN值是什么?我认为arrayTimestampDestro或arrayTimestampSinistro中包含NaN值。@NhutDinhBa您好,谢谢您的回答,arrayTimestampDestro和arrayTimestampSinistro已正确填充。我注意到的是:例如,arrayTimestampDestro和arrayTimestampSinistro的长度为30,因此前15个的TemporaleEdestro有一个值,其他15个为NaN,而对于TemporaleResistro,前15个为NaN,最后15个为NaN
constructor(props){
super(props);
this.state = {
loading: true
};
//....
this.tempoRealeDestro = [];
this.tempoRealeSinistro = [];
}
dataReceived(){
this.dimensioneArrayRaggiunta = this.props.dimensioneArrayRaggiunta;
if(this.checkContatore == false){
this.contatoreDestro = this.props.contatoreTimestampDestro;
this.contatoreSinistro = this.props.contatoreTimestampSinistro;
this.checkContatore = true;
}
this.stopClick();
}