A pure js Array reactive solution with Proxy and Reflect All In One
纯 js 实现数组响应式
demos
const reactiveCallback = (arr) => {
for(const item of arr) {
if(item.hasOwnProperty('id')) {
arr[item.id] = item
}
}
console.log(`new arr =`, arr)
}
const arr = [{id:'one', val:1}, {id:'two', val:2}]
const proxy = new Proxy(arr, {
get: function (target, prop, receiver) {
// delay
setTimeout(() => {
reactiveCallback(arr)
}, 0);
return target[prop];
},
});
proxy.push({id:'three', val: 3})
proxy.pop()
// new arr = (2) [{…}, {…}, one: {…}, two: {…}]
⚠️ 这种赋值骚操作,存在潜在 bug, 使用 ID 作为数组的 key, 导致使用 for 不可遍历访问
arr;
// (2) [{…}, {…}, one: {…}, two: {…}]
for (let item of arr) {
console.log(item)
}
// {id: 'one', val: 1}
// {id: 'two', val: 2}
arr.length
// 2
一种修复 bug 的解决方案
Object.keys(arr)
// (4) ['0', '1', 'one', 'two']
for (let key of Object.keys(arr)) {
console.log(arr[key])
}
// {id: 'one', val: 1}
// {id: 'two', val: 2}
// {id: 'one', val: 1}
// {id: 'two', val: 2}
(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!