gpt4 book ai didi

具有扩展原型(prototype)和 "for-in"循环的 JavaScript native 对象

转载 作者:行者123 更新时间:2023-11-29 17:22:25 24 4
gpt4 key购买 nike

我扩展了 Array 原型(prototype):

if(typeof Array.prototype.filter === 'undefined') Array.prototype.filter = function(fun /*, thisp*/){
var len = this.length;
if(typeof fun != "function") throw new TypeError();

var res = [], thisp = arguments[1];

for(var i=0;i<len;i++){
if(i in this){
var val = this[i]; // in case fun mutates this
if(fun.call(thisp, val, i, this)) res.push(val);
}
}

return res;
};

例如我创建了数组:

var A = [ 1, 2, 3, 4, 5 ];

然后我向它添加了额外的属性,我将使用这些属性:

A.creator = 'Rustam';
A.created = new Date();

如果我将使用 for-in 循环,并且浏览器没有对 Array.filter 的内置支持,它将通过 A.filter.

我是这样认识的:

for(var p in A) {
if (!A.hasOwnProperty(p)) continue
console.log(p)
};

有没有办法在不使用hasOwnProperty的情况下让A.filter隐藏在for-in中?


更新回答。浏览器支持:

  • IE9+
  • FF4+
  • Chrome
  • Opera 11.6+
  • Safari 5+

最佳答案

要定义一个不出现在循环中的属性,使用 Object.defineProperty :

Object.defineProperty(Array.prototype, 'filter', {value:'XYZ'});

这使用名为 filter 的属性扩展了 Array.prototype,该属性具有默认属性描述符,包括 enumerable: false,这会导致属性不出现在 for( .. in ..) 循环中。

引用资料

PS:不适用于旧版浏览器我没有此 API 的浏览器兼容性矩阵。

关于具有扩展原型(prototype)和 "for-in"循环的 JavaScript native 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11739455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com