[英]Extending Object.prototype breaks JavaScript for..in loops, which are used heavily in Google Maps API v3
我正在开发流星项目。 我需要找到对象键表单对象值。 所以我尝试了下面的代码,但浏览器冻结了。
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
var test = {
key1: 42,
key2: 'foo'
};
test.getKeyByValue( 42 ); // returns 'key1'
控制台日志
This site adds property <getKeyByValue> to Object.prototype. Extending Object.prototype breaks JavaScript for..in loops, which are used heavily in Google Maps API v3
控制台消息说这一切都没有。 你可能会通过这样做并在循环机制中打破tte来引发一个infinte循环。
扩展原生对象原型几乎总是一个坏主意。
如果您想要数据对象,只需创建一个数据对象来存储数据
function SimpleMap() { this.list = {}; } SimpleMap.prototype.getKeyByValue = function( value ) { for( var prop in this.list ) { if( this.list.hasOwnProperty( prop ) ) { if( this.list[ prop ] === value ) return prop; } } return null; } SimpleMap.prototype.size = function() { var count = 0; for( var prop in this.list ) { if( this.list.hasOwnProperty( prop ) ) { ++count; } } return count; } SimpleMap.prototype.isEmpty = function() { return this.size() === 0; } SimpleMap.prototype.empty = function() { this.list = {}; } SimpleMap.prototype.put = function(key, value) { this.list[key] = value; } SimpleMap.prototype.get = function(key) { return this.list[key]; } SimpleMap.prototype.remove = function(key) { delete this.list[key]; } var cars = new SimpleMap(); cars.put("volvo","vrooooom"); cars.put("citroen","frut frut frut"); cars.put("reliant","Darn you mr Bean"); var content = document.getElementById('frut'); content.appendChild(document.createTextNode("What does the reliant owner say? "+cars.get("reliant"))); content.appendChild(document.createElement('br')); content.appendChild(document.createTextNode("Who is vroooom? " + cars.getKeyByValue('vrooooom'))); content.appendChild(document.createElement('br')); content.appendChild(document.createTextNode("Is car storage empty? " + cars.isEmpty())); cars.empty() content.appendChild(document.createElement('br')); content.appendChild(document.createTextNode("Is the car storage empty now? " + cars.isEmpty()));
<div id="frut"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.