我有一个变量,它总是一个整数,它的值不时增加和/或减少,从 1 到 5。 我想知道我是否可以以任何方式检测它是上升还是下降,例如:
变量当前为三,如果增加到四,则运行一个函数,如果减少到二,则运行另一个函数。
可以吗?
最佳答案
以下四种方法的工作取决于浏览器兼容性的支持,这篇文章确实花了我一段时间,但它也教会了我什么___
/strong> 确实如此,我希望我列出了大多数方法,如果您知道更多,可以发布答案。 不过,如果您能在评论中发布您的方法,我会非常高兴,这样我就可以将它添加到这个答案中。干杯!
1 使用Object.observe:
Object.observe(i, function(b){ b.object[change.name] > b.type ? console.log('decreased') : console.log('increased'); });
关于Object.observe
的补充说明
如果你想在 Chrome 33 中启用它,
访问 chrome://flags/
并启用 Enable Experimental JavaScript
2 使用setInterval:
var i = 4;
var a = i;
setInterval(function()
{
if(i != a) a > i ? console.log('decreased') : console.log('increased');
}, 1000);
i = 10;
应该在一秒钟内记录“增加”。
3 使用Object.watch:
var i = {i:5};
i.watch("i", function (id, oldval, newval) {
newval > oldval ? console.log('decreased') : console.log('increased');
return newval;
});
关于Object.watch
的补充说明
要支持更多浏览器,添加这个脚本:
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;
}
});
}
取自https://gist.github.com/eligrey/384583
4.使用自定义值集函数:
i = 4;
function setValue(obj, val)
{
val < obj ? console.log('decrease') : console.log('increase');
obj = val;
}
setValue(i, 10);
应该记录“增加”。
其中大部分要求变量是一个对象,所以我宁愿像方法2 中看到的那样随着时间的推移进行检测。
关于javascript - 我可以检测 javascript 中的变量值是增加还是减少吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21125195/