问题描述
是否可以通过附加方法或属性或使用 console.log()
捕获某些内容来控制 console.dir()
和 Proxy
为对象打印/显示的内容?
为了快乐,我对使用 Proxy
的 Reference to slice of an array 的答案进行了过度设计。据我所知,我一切正常除了调用 console.log()
和 console.dir()
时发生的情况。
const arr = [1,2,3,4,5];
const slice = array.slicePtr(1,4);
console.log([ ...slice ]); // ✅ [2,4]
console.log(slice); // ❌ [1,5]
console.log(slice.toString()); // ✅ 2,4
console.log(JSON.stringify(slice)); // ✅ [2,4]
以下是 array.slicePtr()
的完整代码,尽管 Stack Overflow 的代码段运行器似乎以 console.log(slice)
失败。打开 DevTools 并运行代码片段,您将看到它的作用。
Array.prototype.slicePtr = function(startIdx,endIdx = this.length) {
if (startIdx > endIdx) {
throw new Error('startIdx must not be less than endIdx');
}
endIdx = endIdx == null ? this.length : endIdx;
const self = this;
function contains(idx) {
return idx > 0 && idx < endIdx;
}
const proxy = new Proxy(this,{
get(target,prop,receiver) {
// symbols can't be converted to numbers,so handle them first
if (typeof prop === 'symbol') {
switch (prop) {
case Symbol.iterator:
return function*() {
for (let i = startIdx; i < endIdx; i++) {
yield self[i];
}
}
}
}
const idx = startIdx + Number(prop);
if (!isNaN(idx)) {
if (!contains(idx)) {
return undefined;
}
return Reflect.get(target,idx,receiver);
}
switch (prop) {
case 'splice':
return function splice(start,delCount,...items) {
endIdx += items.length - delCount;
return self.splice(start + startIdx,...items);
}
case 'length':
return endIdx - startIdx;
case 'pop':
return function pop() {
return proxy.splice(proxy.length - 1,1)[0];
}
case 'push':
return function push(...items) {
proxy.splice(proxy.length,...items);
return proxy[proxy.length - 1];
}
case 'shift':
return function shift() {
return proxy.splice(0,1)[0];
}
case 'unshift':
return function unshift(...items) {
proxy.splice(startIdx,...items);
return proxy[proxy.length - 1];
}
}
return Reflect.get(target,receiver);
},set(target,value,receiver) {
if (typeof prop !== 'symbol') {
const idx = startIdx + Number(prop);
if (!isNaN(idx)) {
if (Number.isFinite(idx) && Number.isInteger(idx) && Number(prop) >= proxy.length) {
endIdx = idx + 1;
}
return Reflect.set(target,receiver);
}
}
switch (prop) {
case 'length':
endIdx = startIdx + value;
if (endIdx > self.length) {
self.length = endIdx;
}
return value;
}
return Reflect.set(target,});
return proxy;
}
const arr = [ 1,5 ];
const slice = arr.slicePtr(1,4);
console.log([...slice]);
console.log(slice);
console.log(slice.toString());
console.log(JSON.stringify(slice));
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)