我可以检测 javascript 中的变量是增加还是减少值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21125195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:07:54  来源:igfitidea点击:

Can I detect if a variable in javascript increases or decreases in value?

javascriptjqueryvariablesvar

提问by NepsName

I have a a variable, which always is an integer, that increases and/or decreases in value from time to time, goes from 1-5. I wanted to know if I can, in any way, detect if it goes up or down, for example:

我有一个变量,它总是一个整数,它的值不时增加和/或减少,从 1 到 5。我想知道我是否可以以任何方式检测它是上升还是下降,例如:

The variable is currently at three, if it increases to four, it runs a function, but if it decreases to two, it runs another function.

变量当前为 3,如果增加到 4,它运行一个函数,但如果它减少到 2,它运行另一个函数。

Can that be done?

可以做到吗?

采纳答案by isherwood

Sure, but you'll have to check it periodically. Since you didn't provide code, I won't, either. :-)

当然可以,但您必须定期检查它。既然你没有提供代码,我也不会。:-)

  1. Set a second variable equal to the first
  2. Check the second against the first at regular intervals (or upon some event)
  3. Respond accordingly
  1. 设置第二个变量等于第一个
  2. 定期(或在某些事件中)检查第二个和第一个
  3. 做出相应的回应

As was mentioned in the comments, there are better ways, such as running functionality alongside (or as a callback to) whatever changes the variable's value in the first place.

正如评论中提到的,有更好的方法,例如在首先更改变量值的任何内容旁边(或作为回调)运行功能。

回答by Cilan

The following four methods will work depending on support by browser compatibility, and this post didtake me a while, but it also taught me what ___does, and I hope I listed most methods, and if you know more, you could post an answer. However,it would be greatful of you to post your method in the comments so I can add it to this answer. Cheers!

根据浏览器兼容性的支持,以下四种方法会起作用,这篇文章确实花了我一段时间,但它也教会了我什么___方法,我希望我列出了大多数方法,如果你知道更多,你可以发布答案。 但是,如果您能在评论中发布您的方法,我就可以将其添加到此答案中。干杯!



1Use Object.observe:

1使用Object.observe:

Object.observe(i, function(b){ b.object[change.name] > b.type ? console.log('decreased') : console.log('increased'); });

Additional notes about Object.observe

关于的附加说明 Object.observe

If you like to enable it in Chrome 33,

如果您想在 Chrome 33 中启用它,

Visit chrome://flags/

访问 chrome://flags/

And enable Enable Experimental JavaScript

并启用启用实验性 JavaScript



2Use setInterval:

2使用setInterval:

var i = 4;
var a = i;
setInterval(function()
{
    if(i != a) a > i ? console.log('decreased') : console.log('increased');
}, 1000);
i = 10;

should log 'increase' in one second.

应该在一秒钟内记录“增加”。



3Use Object.watch:

3使用Object.watch:

var i = {i:5};
i.watch("i", function (id, oldval, newval) {
    newval > oldval ? console.log('decreased') : console.log('increased');
    return newval;
});

Additional notes about Object.watch

关于的附加说明 Object.watch

To support more browsers, add this script:

要支持更多浏览器,请添加以下脚本:

if (!Object.prototype.watch) {
    Object.defineProperty(Object.prototype, "watch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop, handler) {
            var
              oldval = this[prop]
            , newval = oldval
            , getter = function () {
                return newval;
            }
            , setter = function (val) {
                oldval = newval;
                return newval = handler.call(this, prop, oldval, val);
            }
            ;

            if (delete this[prop]) { // can't watch constants
                Object.defineProperty(this, prop, {
                      get: getter
                    , set: setter
                    , enumerable: true
                    , configurable: true
                });
            }
        }
    });
}

// object.unwatch
if (!Object.prototype.unwatch) {
    Object.defineProperty(Object.prototype, "unwatch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop) {
            var val = this[prop];
            delete this[prop]; // remove accessors
            this[prop] = val;
        }
    });
}

obtained from https://gist.github.com/eligrey/384583

https://gist.github.com/eligrey/384583获得



4.Use a custom value set function:

4.使用自定义值设置函数:

i = 4;

function setValue(obj, val)
{
    val < obj ? console.log('decrease') : console.log('increase');
    obj = val;
}

setValue(i, 10);

should log 'increase'.

应该记录“增加”。



Most of these require the variable to be an Object,so I'd rather detect over time as seen in method 2.

其中大多数要求变量是一个对象,所以我宁愿随着时间的推移进行检测,如方法2 所示。

回答by maxedison

Rather than detecting if a variable changes, I would use a function to modify the variable. That way, the function can then check if the value has changed and call the new function if it has. Something like:

我不会检测变量是否发生变化,而是使用函数来修改变量。这样,函数就可以检查值是否已更改,如果已更改,则调用新函数。就像是:

var triggerVariable;

function changeVariable(newVal){
    if(triggerVariable !== newVal){
        triggerVariable = newVal;
        callFunction();
    }
}

function callFunction(){
    alert('variable changed!');
}

changeVariable(10);

回答by D. Patrick

Object.observe is supposed to be well supported. You can track your state as you please (probably in a closure of some sort).

Object.observe 应该得到很好的支持。您可以随心所欲地跟踪您的状态(可能在某种关闭状态下)。

http://updates.html5rocks.com/2012/11/Respond-to-change-with-Object-observe

http://updates.html5rocks.com/2012/11/Respond-to-change-with-Object-observe

回答by Peter Bankuti

you can also create a class for this special variable, and write custom functions for mathematical functions with callback. here is an example with the addfunction

您还可以为这个特殊变量创建一个类,并为带有回调的数学函数编写自定义函数。这是添加函数的示例

function specVal (value) 
{
  this.onChange = null;
  this.value = value;
  this.val = function() 
  {
    return this.value;
  };

  this.add = function(i)
  {  
    this.value += i;
    if (this.onChange != null)
      this.onChange(this);
    return this;
  }
}

function somethingChanged(val)
{
  alert('changed: ' + val.val());
}

myValue = new specVal(10);
myValue.onChange = somethingChanged;
myValue.add(5);
myValue.add(4);

回答by CodeToad

I would either use an MV* frameworkas suggested (knockout is a lightweight option) or never change the variable directly. Use a setter function that changes its value and triggers a custom event each time. JQueryexample:

我要么按照建议使用MV* 框架(knockout 是一个轻量级的选项),要么从不直接更改变量。使用 setter 函数更改其值并每次触发自定义事件。 jQuery示例:

Function setMyVar(val){  
    if(_myVar  !== val){
    _myVar = val;
    $('#anyelement').triggerHandler('myvarupdated', [myVar]);
    }
}

回答by Trinker

Very similar to prior answers.

与之前的答案非常相似。

  1. Set a second variable equal to the first
  2. Check the second against the first at regular intervals (or upon some event)
  3. Respond accordingly
  1. 设置第二个变量等于第一个
  2. 定期(或在某些事件中)检查第二个和第一个
  3. 做出相应的回应

But organise it differently. And make sure you leave the last variable outside of the function. Moreover, at the end of your ifconditional statements update the value for the one being checked for changes.

但以不同的方式组织它。并确保将最后一个变量留在函数之外。此外,在if条件语句的末尾更新被检查更改的值。

Hope it helps!

希望能帮助到你!

var lastValue = 0;
$(function () {


    if (lastValue > originalValue){
        console.log ("Increasing");
    }
    else if (lastValue < originalValue) {
        console.log("Decreasing");
    }
    lastValue = originalValue;            

});

Check this JSFiddle

检查这个JSFiddle