Javascript 变量的值是否已更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3051114/
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-08-23 03:06:29  来源:igfitidea点击:

value of variable has changed or not

javascript

提问by Niraj Choubey

how to find whether a value of variable is changed or not in javascript .

如何在 javascript 中查找变量的值是否已更改。

回答by bezmax

Ehm?

嗯?

var testVariable = 10;
var oldVar = testVariable;

...
if (oldVar != testVariable)
alert("testVariable has changed!");

And no, there is no magical "var.hasChanged()" nor "var.modifyDate()" in Javascript unless you code it yourself.

不,Javascript 中没有神奇的“var.hasChanged()”或“var.modifyDate()”,除非您自己编写代码。

回答by meouw

There is a way to watch variables for changes: Object::watch- some code below

有一种方法可以观察变量的变化:Object::watch- 下面的一些代码

/*
For global scope
*/

// won't work if you use the 'var' keyword
x = 10;

window.watch( "x", function( id, oldVal, newVal ){
    alert( id+' changed from '+oldVal+' to '+newVal );

    // you must return the new value or else the assignment will not work
    // you can change the value of newVal if you like
    return newVal;
});

x = 20; //alerts: x changed from 10 to 20


/*
For a local scope (better as always)
*/
var myObj = {}

//you can watch properties that don't exist yet
myObj.watch( 'p', function( id, oldVal, newVal ) {
    alert( 'the property myObj::'+id+' changed from '+oldVal+' to '+newVal );
});


myObj.p = 'hello'; //alerts: the property myObj::p changed from undefined to hello
myObj.p = 'world'; //alerts: the property myObj::p changed from hello to world

// stop watching
myObj.unwatch('p');

回答by Solomon Ucko

Using gettersand setters:

使用gettersetter

var _variable;
get variable() {
    return _variable;
}
set variable(value) {
    _variable = value;
    // variable changed
}

or if you don't need the value of the variable later:

或者如果您以后不需要变量的值:

set variable(value) {
    // variable changed
}

回答by User 1034

If you are a firefox user you can check using firebug. If you are using IE we can put alert statements and check the values of the variables.

如果您是 firefox 用户,则可以使用 firebug 进行检查。如果您使用的是 IE,我们可以放置警报语句并检查变量的值。

回答by deceze

By comparing it to a known state to see if it differs. If you're looking for something like variable.hasChanged, I'm pretty sure that doesn't exist.

通过将其与已知状态进行比较以查看它是否有所不同。如果您正在寻找类似的东西variable.hasChanged,我很确定它不存在。