JavaScript: in, hasOwnProperty, delete, for/in

in operator

Determining whether an object has a property
as long as the object that owns the property, it will return true, otherwise false

var point = { x:1, y:1 };
alert( 'x' in point );  //true

var arr = ['one', 'two'];
alert( 'kang' in arr );  //false
alert( '1' in arr );  //true
alert( 'push' in arr );  //true

was fn = function () {};
fn.prototype.site = 'cnblogs.com';
var obj = new fn ();
alert( 'site' in obj );  //true

hasOwnProperty

Determining whether the object has a property. This property must have their own, that is non-inherited.

There o = {};
o.name = 'object';
alert (o.hasOwnProperty ( 'kang')); // false: absent
alert (o.hasOwnProperty ( 'toString')); // false: 'toString' method inherited from 'Object'
alert( o.hasOwnProperty('name') );	//true

alert( Math.hasOwnProperty("kang") );	//false
alert( Math.hasOwnProperty("cos") );	//true;
alert (Math.hasOwnProperty ( "toString")); // false: 'toString' method inherited from 'Object'

was the base = function () {
    this.name = 'Rain Man';
};
base.prototype.site = 'cnblogs.com';
There o = new Base ();
alert (o.hasOwnProperty ( 'site')); // false: inherited
alert( o.hasOwnProperty('name') );	//true

delete operator

Remove object's properties, delete can not be used for / in enumerated attribute deleted using hasOwnProperty () detects the property returns false.
Delete elements of the array, length of the array after deletion does not change, can not be used for / in enumerated elements that were removed; the elements will really delete array shift (), pop (), splice () in

var point = { x:1, y:1 };
delete point.x;  //{ y:1 }

var arr = ['one', 'two'];
delete arr[0];  //[undefined, 'two'] 

for/in

Object attributes enumerated
attributes of the object is not used for / in to output, for example: inside, can be user-defined, inherited from the constructor prototype may also be enumerated

var arr = ['one', 'two'];
arr.author = 'rainman';
push, pop and other methods // not enumerate the array, because these methods are internal
for( var i in arr ) ist(arr[i]);    //'one'、'two'、'rainman'

was Blog = function () {};
Blog.prototype.site = 'cnblogs.com';
Lining var = new Blog ();
for (var i and cladding) ist (pads [i]); //'cnblogs.com '

was RM = function () {};
RM.prototype = new Blog();
RM.prototype.url = 'http://rainman.cnblogs.com'
was ORM = new RM ();

for( var i in oRM ){
    ist(i + ':'+ oRM[i]);	//'url:http://rainman.cnblogs.com'、site:cnblogs.com
}

Reproduced in: https: //www.cnblogs.com/rainman/archive/2010/08/12/1798022.html

Guess you like

Origin blog.csdn.net/weixin_34301132/article/details/93561017