.notion vs.[]notation |插入到文本对象中

. notaion vs. [] notation | Inserting into a Text Object

本文关键字:文本 对象 插入 vs notation notion      更新时间:2023-09-26

在下面提到的代码行上,我在点表示法和括号表示法之间移动。JavaScript - The Good Parts建议默认使用点表示法。

如何更新此代码以使用点表示法。请注意,form_elements包含作为键的表单输入名称,这些名称是有效的JavaScript标识符(它们仅使用字母数字字符)。

根据JavaScript - The Good Parts,这意味着它们可以与点符号一起使用。

Su.text = function (form_elements) {
    this.text_object = {};
    var key;
    for (key in form_elements) { //*u
        if (form_elements.hasOwnProperty(key)) {
            this.text_object[form_elements[key].name] = form_elements[key].value; // this line
        }
    }
    return this;
};

括号表示法用于编译时未知的键名,例如您的情况。所以你必须在这里使用它。

 aaa.foo  // dot notation, name of the field is "foo"
 aaa[foo] // bracket notation, name of the field is stored in variable foo

你想避免的是

aaa["foo"]  // just ugly, necessary only if the field name is complicated
aaa["space and 123 in there"]   // like here