39, Property traversal

Source: Internet
Author: User
Tags hasownproperty
Find out if object obj is not on the prototype chain (note that there is also a space behind the colon of the test example)
1, returns the array, the format is Key:value
2, the result array does not require the order
Enter an example:
var C = function () {This.foo = ' bar '; this.baz = ' Bim ';}; C.prototype.bop = ' Bip '; Iterate (new C ());

Output Example:
["Foo:bar", "Baz:bim"]
Method One: for...in + hasownproperty can use for-in to traverse the properties in the object, hasOwnProperty method can return a Boolean value, Indicates whether an object has a property of the specified nameThis method cannot check whether the object's prototype chain has this property, which must be a property of the object itself.
function iterate (obj) {
     var arr = [];
     Use For-in to traverse object Properties
     for (var key in obj) {
         //To determine whether the key is the property of the object itself
         if (Obj.hasownproperty (key)) {
             // Store attributes and values in an array by format
             Arr.push (key+ ": +obj[key]);
         }
     return arr;
 }

Method Two:
function iterate (obj) {return
    object.getownpropertynames (obj). Map (function (key) {return
        key+ ":" +obj[key ];
    });
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.