如何更改以下代码以不使用eval?

gan*_*gul 2 javascript json eval

var settings = {};

$(".js-gen-settings").each(function(){
    var date;

    if (($(this).attr("type") === "checkbox") || ($(this).attr("type") === "radio")){//if its a checkbox
        eval("settings."+this.name+" = "+$(this).is(":checked"));
    }else{
        date = $(this).val();
        if (date == ""){
            eval("settings." + this.name + " = null");
        }else{
            eval("settings." + this.name + " = '" + date + "'");
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

将使用ajax将一个JSON.stringify版本settings发送到服务器.

小智 6

如果要动态修改对象的属性,只需将名称放在[括号中即可].

settings[this.name] = null

settings[this.name] = date;

settings[this.name] = $(this).is(":checked");
Run Code Online (Sandbox Code Playgroud)