简体   繁体   中英

Why does my valueOf() method not return the value?

I'm having a little problem with the valueOf() method of an object. I've got an Array with objects and object literals in it. Say it's var Books = [ {"name": "SomeBook"}, {"name": "SomeOtherBook"} ] . Now I want to write all the literals into some text-inputs via

var i = 0;
book = Books[0];
for (var property in book) {
    if (book.hasOwnProperty(property)) {
        editInputs[i].value = property.valueOf();
        //console.log(property.valueOf());
    }
    i++;
}

Why is my output the object's name? When I de-comment the log(), I also get "name" instead of SomeBook. Yet, if I use

editInputs[0].value = book.name;

It inserts SomeBook .

Why? I don't want to write every field in a single line...

Thanks in advance!

property is a string containing the name of the property.

valueOf gives you the primitive value of that, which is still a string containing the name of the property.

If you want to use that string to get the value of the property name which matches the string stored in property you need to use:

book[property]

The variable in a for loop is just a string. valueOf() just returns the primitive value of the object, but for a string, you just get the string back.

You have to do book[property] instead. There isn't really a better way to do it.

Instead of

editInputs[i].value = property.valueOf(); 

you should use

editInputs[i].value = book[property];

If property is a property of your book object, you will just need to call:

book[property]

To get its value, because .valueOf() returns the primitive value of the specified object as you can see it in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM