JS知识点总结
文章目录
一、如何监听数组的改变?
利用Proxy
可以来监听数组的length
属性,当push
或者pop
的时候,会触发setter
:
const proxyArr = new Proxy(unkownArr, {
set(target, prop, value, receiver) {
if (prop === 'length') {
console.log('set new value', value);
return false;
}
console.log('receiver', receiver);
return Reflect.set(...arguments);
}
});
那要监听数组某一项的变化呢?那就是prop !== 'length'
的情况了:
const proxyArr = new Proxy(unkownArr, {
set(target, prop, value, receiver) {
if (prop !== 'length') {
console.log('set new value', value);
return false;
}
console.log('receiver', receiver);
return Reflect.set(...arguments);
}
});