1

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')
}

Expected output

Array value changed

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')
}
4
  • 1
    why not use a function to change the value and call print together? Commented Jan 29, 2018 at 12:01
  • For your reference, I gave these inputs. I can not directly call this function Commented Jan 29, 2018 at 12:03
  • I think you might be after using a proxy -> stackoverflow.com/questions/35610242/… Commented Jan 29, 2018 at 12:11
  • I will check and let you know here Commented Jan 29, 2018 at 12:13

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.