变量在js中返回为NaN

我正在旋转模型。当我单击开始按钮时,它从0

开始

start = animateAssembly

我正在尝试从width恢复。 width的值将在那里存在,而我的动画将从此处开始。

resume = resumeAssembly

但是宽度变量在框架内返回为NaN

并且没有传递到resumeAssembly

animateAssembly: function() {

        var element = document.getElementById("myBar");

        this.width = 1;

        clearInterval(this.interval);
        this.interval = setInterval(frame,100);

        //here my width shows number
        console.log(typeof this.width);

        function frame() {
            if (this.width >= 100) {
                console.log(typeof this.width);
                clearInterval(this.interval);
            } else {
                this.width++;
                console.log(typeof parseInt(this.width));
                console.log(typeof this.width);

                //here it shows as NaN
                element.style.width = parseInt(this.width) + '%';
                element.innerHTML = parseInt(this.width) + "%";

            }
        }

    },pauseAssembly: function() {
        clearInterval(this.interval);
        this.tweening.stop();

    },resumeAssembly: function() {
        var element = document.getElementById("myBar");
        element.style.width = this.width + '%';
        element.innerHTML = this.width + "%";

    },
iCMS 回答:变量在js中返回为NaN

函数this中的frame()指的是frame()函数的上下文,而不是初始化this.width的父函数的上下文。

为避免这种情况,您可以将框架函数初始化为箭头函数:

const frame = () => {
    // here,'this' refers to the parent's scope
}
,

这是一个功能范围问题。 在您的框架内,this可能并没有体现您的想法。 它可能是针对interval本身。 因此,在赋予功能

this.interval = setInterval(frame.bind(this),100); // bind current target 
,

function frame()内部,您有一个不同的this。要么使用箭头语法

const frame = () => {}

或更改呼叫站点。

this.interval = setInterval(frame.bind(this),100);
,

library(dplyr) lookup <- df1 %>% inner_join(df2,by = c("ID_EG" = "ID")) %>% select(-Group) %>% distinct() # ID_EG ID_CG Year Month # 1 800057 834341 2008 2 # 2 800119 897177 2014 10 # 3 800125 834011 2010 5 df2 %>% left_join(lookup,by = c("ID" = "ID_CG")) %>% mutate( Year = coalesce(Year.x,Year.y),Month = coalesce(Month.x,Month.y) ) %>% select(!ends_with(".x") & !ends_with(".y"),-ID_EG) 内部访问 ID Group Year Month 1 800057 1 2008 2 2 800057 1 2008 2 3 800057 1 2008 2 4 800057 1 2008 2 5 800057 1 2008 2 6 800119 1 2014 10 7 800119 1 2014 10 8 800119 1 2014 10 9 834011 0 2010 5 10 834011 0 2010 5 11 834341 0 2008 2 12 834341 0 2008 2 13 834341 0 2008 2 14 834341 0 2008 2 15 834341 0 2008 2 16 800125 1 2010 5 17 800125 1 2010 5 18 897177 0 2014 10 19 897177 0 2014 10 20 897177 0 2014 10 时存在范围问题。因为this.width内的function frame()this内的frame不同。

因此,当执行this函数时,animateAssembly将是frame。因此this.width将是undefined

这可以通过两种不同的方式解决

  • 使用箭头功能,以使parseInt(undefined)函数内部的NaN与下面一样
this
  • 您可以frame对该函数进行const frame = () => { //rest of the code } 的引用,如下所示
bind

希望这会有所帮助。

本文链接:https://www.f2er.com/2023143.html

大家都在问