对象属性未定义但存在

时间:2017-01-29 11:14:11

标签: javascript

我刚看到一个奇怪的错误。

所以我有:

HTML

<div class="mui-textfield mui-textfield--float-label">
    <input id="registration-firstname" type="text" required>
    <label>First name</label>
</div>
<div class="mui-textfield mui-textfield--float-label">
    <input id="registration-last-name" type="text" required>
    <label>Last name</label>
</div>
<div class="mui-textfield mui-textfield--float-label">
    <input id="registration-email" type="email" required>
    <label>Email address</label>
</div>
<div class="mui-select">
    <select id="registration-role">
        <option>user</option>
        <option>courier</option>
    </select>
    <label>Role</label>
</div>

的javascript

var elements = {
        messages : {
            ...non relevant object...
        },
        forms : {
            registration : {
                "firstname" :  document.getElementById('registration-firstname'),
                "lastname " :  document.getElementById('registration-last-name'),
                "email" :  document.getElementById('registration-email'),
                "role" :  document.getElementById('registration-role')
            }
        }
}

问题

如果我这样做:

的console.log(elements.form.registration);

它将打印:

Object { firstname: <input#registration-firstname>, lastname : <input#registration-last-name>, email: <input#registration-email>, role: <select#registration-role>, password: <input#registration-password> }

很明显,lastname属性存在。但如果我这样做

console.log(elements.forms.registration.lastname)

它会打印出来:

undefined

我已经检查过lastname属性是否存在,我甚至试过

console.log(Object.keys(elements.forms.registration))

并打印

Array [ "firstname", "lastname ", "email", "role", "password" ]

是什么让事情更加奇怪 - 给定对象中的任何其他属性都不会出现问题。

2 个答案:

答案 0 :(得分:2)

找到它。

中有额外的尾随空格
//       ↓
"lastname "

答案 1 :(得分:1)

尽管使用""引号定义对象没有区别,但请更改此

registration : {
                "firstname" :  document.getElementById('registration-firstname'),
                "lastname " :  document.getElementById('registration-last-name'),
                "email" :  document.getElementById('registration-email'),
                "role" :  document.getElementById('registration-role')
            }

registration : {
                firstname :  document.getElementById('registration-firstname'),
                lastname :  document.getElementById('registration-last-name'),
                email :  document.getElementById('registration-email'),
                role :  document.getElementById('registration-role')
            }