简体   繁体   English

为什么我的valueOf()方法不返回值?

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

I'm having a little problem with the valueOf() method of an object. 我在使用对象的valueOf()方法时遇到了一些问题。 I've got an Array with objects and object literals in it. 我有一个包含对象和对象文字的数组。 Say it's var Books = [ {"name": "SomeBook"}, {"name": "SomeOtherBook"} ] . 假设是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. 当我注释log()时,我也会得到“名称”而不是SomeBook。 Yet, if I use 但是,如果我使用

editInputs[0].value = book.name;

It inserts SomeBook . 它插入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. property是一个包含属性名称的字符串。

valueOf gives you the primitive value of that, which is still a string containing the name of the property. valueOf为您提供该值的原始值,该值仍然是包含属性名称的字符串。

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: 如果要使用该字符串来获取与存储在property中的字符串匹配的属性名称的值,则需要使用:

book[property]

The variable in a for loop is just a string. for循环中的变量只是一个字符串。 valueOf() just returns the primitive value of the object, but for a string, you just get the string back. valueOf()仅返回对象的原始值,但是对于字符串,只需将字符串取回即可。

You have to do book[property] instead. 您必须改为book[property] 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: 如果property是您的book对象的属性,则只需调用:

book[property]

To get its value, because .valueOf() returns the primitive value of the specified object as you can see it in the documentation. 为了获得其值,因为.valueOf()返回指定对象的原始值,如您在文档中所见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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