数组节点js中数据更改的事件侦听器 [英] Event listener on data change in array node js

查看:80
本文介绍了数组节点js中数据更改的事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为3的数组。当数组值更改时,我需要动态调用一个函数。知道吗?

I have an array with size of 3. I need to call a function dynamically when the array value is changed. Any idea?

var arr = ["","",""];

arr[0] = 'first value is chagned';
arr[1] = 'second value is chagned';


function arrFunction(){
    console.log('Array value changed')
}

预期输出

数组值已更改

数组值已更改

我知道我们可以通过调用函数来实现直接像下面。作为参考,我提供了这些信息。我不能直接调用下面的函数

I know we can achive this by calling function directly like below. For your reference, I gave these inputs. I can not directly call function like below

var arr = ["","",""];

arr[0] = 'first value is chagned';
arrFunction()
arr[1] = 'second value is chagned';
arrFunction()

function arrFunction(){
    console.log('Array value changed')
}


推荐答案

如果您的目标支持 代理 这很容易做到:

if your target support Proxies this is easy to do:

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';

这篇关于数组节点js中数据更改的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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