“The `Array.prototype` contains unexpected enumerable properties: add; thus breaking e.g. `for...in`

近期项目中会使用到pdf.js 做pdf文件的预览功能(完整代码在文末,前文主要简述处理过程和目的)

正常使用官网的例子

不出所料的没有正常渲染 wtf??

看看控制台 ok 一排红色

“The `Array.prototype` contains unexpected enumerable properties: add; thus breaking e.g. `for...in`_第1张图片
ok 读读提示 数组的原型有个异常的属性 add, 然后终端了for…in循环
非常好 娱乐的坐牢时间开始了
先是测试包的问题 一直不断的切版本 基本都是这个错
然后! 面向百度编程 (不愧是本吊)
文章找不到了 但是大概内容是 pdf.js 对数组原型上的方法做了检测 不能添加除原始属性上的其他属性

然后 打印Array.prototype 看看多余的属性
“The `Array.prototype` contains unexpected enumerable properties: add; thus breaking e.g. `for...in`_第2张图片
可以看到有许多不是原始属性的方法 删掉就好咯

可是 问题在于怎么删 是申明静态数组去迭代删除 还是其他方式呢
作为一名开发 好的代码必然是需要规避硬编码的 同时 如果后面又有新增的非原始属性 那怎么办

不废话了 直接上代码 先读非原始 也就是直接属性

console.log(Array.prototype)
let unexpectedProperties = []; // 非原有属性数组
for (let key in Array.prototype) {
    if (!Array.prototype.hasOwnProperty(key)) continue;
    unexpectedProperties.push(key);
};
console.log(unexpectedProperties);

“The `Array.prototype` contains unexpected enumerable properties: add; thus breaking e.g. `for...in`_第3张图片

控制台上打印出了直接属性 剩下就是删除了

unexpectedProperties.forEach(v => delete Array.prototype[v]);

没在for…in迭代中直接删而选择数组中转是有目的的

接下来打开控制台 页面正常了 左侧的pdf完全渲染回来了
“The `Array.prototype` contains unexpected enumerable properties: add; thus breaking e.g. `for...in`_第4张图片

但是 还没有结束 有始就要有终 删掉的也要拿回来
上所有完整代码再说明

// 非原有属性数组
let _unexpectedProperties = [], _logArr = []; 
for (let key in Array.prototype) {
    if (!Array.prototype.hasOwnProperty(key)) continue;
    // 存放直接属性
    _unexpectedProperties.push(key);
};
// 存放原始键 原始方法
_logArr = _unexpectedProperties.map(v => ({ [v]: Array.prototype[v] }));
// 删除直接属性
_unexpectedProperties.forEach(v => delete Array.prototype[v]);

// 渲染pdf
pdfjsLib.getDocument(pdfUrl).promise.then(doc => {
	// 渲染完后归还直接属性
    Object.assign(Array.prototype, ..._logArr);
});

关键代码就在于 _logArr数组对方法的记录 同时在渲染pdf后 我们将删掉的属性重新挂在回Array.prototype

好了 结束 有帮助到你的话 动动您的小手点点赞 ♥

这里放一个pdf.js 渲染全部分页的用例

你可能感兴趣的:(javascript,pdf,bug,原型模式)