我有一个大小为3的数组。我需要在数组值更改时动态调用函数。有什么想法吗?
var arr = ["","",""];
arr[0] = 'first value is chagned';
arr[1] = 'second value is chagned';
function arrFunction(){
console.log('Array value changed')
}
预期输出
数组值已更改
数组值已更改
我知道我们可以通过直接调用函数来实现这一点,如下所示。作为参考,我提供了这些输入。我不能直接调用下面的函数
var arr = ["","",""];
arr[0] = 'first value is chagned';
arrFunction()
arr[1] = 'second value is chagned';
arrFunction()
function arrFunction(){
console.log('Array value changed')
}
答案 0 :(得分:2)
如果你的目标支持Proxies
这很容易做到:
let observe = (obj, fn) => new Proxy(obj, {
set(obj, key, val) {
obj[key] = val;
fn(obj)
}
});
arr = observe(['', '', ''], arr => {
console.log('arr changed! ', arr)
});
arr[0] = 'first value is chagned';
arr[1] = 'second value is chagned';