Finding sub properties of javascript object

不想你离开。 提交于 2019-12-25 12:35:09

问题


My code ise this:

var cem = { "name": "cem topkaya" };
f_PropertyBul(cem);
function f_PropertyBul(obj) {

    for (var prop in obj) {

        document.writeln(obj + " prop: " + prop + " propertyIsEnumerable:" + obj.propertyIsEnumerable(prop) + "<br/>");

        if (obj.propertyIsEnumerable(prop)) {            
            f_PropertyBul(obj[prop]);            
        }

    }
 }

I know there are a lot of question and answers about that but i didn't get why i get this result :

[object Object] prop: isim enumaret: true
cem topkaya prop: 0 enumaret: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
c prop: 0 propertyIsEnumerable: true
.
..
....

At the end, i am reaching the last property as a string. But it still says that it has propertyIsEnumareble true .

I just want to send an object and search an property name and its value. when it found i just want to break search and return back one property of my JSON object.


回答1:


Strings are enumerable. For example:

var str = "string"
for (var c in str) {
   console.log(str[c]);
}

Returns:

s
t
r
i
n
g

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/propertyIsEnumerable

This method can determine whether the specified property in an object can be enumerated by a for...in loop

If you want to exclude strings, add a check for typeof prop !== "string" in the if statement.



来源:https://stackoverflow.com/questions/3358811/finding-sub-properties-of-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!