检查是否已设置变量不起作用 [英] Checking if a variable has been set is not working

查看:97
本文介绍了检查是否已设置变量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在没有设置变量时才尝试设置变量。出于某种原因,无论变量是否已设置,我用来确定变量是否已设置的逻辑似乎都运行。

I am trying to set a variable initially only if it has not been set. For some reason the logic I'm using to determine whether the variable has been set seems to run even regardless of whether the variable has been set.

我的代码是

var l0 = -210;

function add(){
  var lThis;
  if (lThis == null){
     lThis = l0;
     console.log('set lThis to '+ lThis);
  }
  lThis ++;
}

var incrementInterval = setInterval(add, 33);

每次间隔运行时,控制台都会记录将lThis设置为-210,因此if( l这= = null)好像什么都不做

The console logs "set lThis to -210" every time the interval runs, so the "if (lThis == null)" seems to be doing nothing

参见关于codepen的例子

推荐答案

使用setInterval函数add从开始每隔33ms执行一次,做全部重新创建功能范围,包括lThis。我想你想要实现的是在函数中每次调用lshis时加1。实现这一目标的方法之一是通过以下方式使用闭包:

With setInterval function add is executed every 33ms from the start, do the whole function scope is recreated, including lThis. I suppose what you want to achieve is to add 1 on every call to lThis within function. One of ways to achieve that is using closure in the following way:

var l0 = -210;

function thunkAdd(){
  var lThis = l0;
  console.log('set lThis to '+ lThis);
  return function inc() {
    console.log(lThis);
    return lThis ++;
  }
}

var incrementInterval = setInterval(thunkAdd(), 33);

注意,这是编写JavaScript的旧方法,使用新的ES6语法可以实现很多更紧凑的形式:

Note, this is the old way of writing JavaScript, with new ES6 syntax it can be achieved in much more compact form:

const l0=-210;

function *add() {
  let lThis = l0;
  while (true) yield lThis++;
}

const lAdd = add()
const incrementInterval = setInterval(() => {console.log(lAdd.next())}, 33);

这篇关于检查是否已设置变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆