Javascript 从循环中添加对象属性无效

Javascript 从循环中添加对象属性无效,javascript,jquery,Javascript,Jquery,我正在尝试从“for循环”添加属性名和值。但是,它在对象情况下不起作用。但如果我使用HTML表单,它就可以正常工作 var interestListsObj = {} interestLoop:function(interestList){ var text = ""; for(var i=0; i<interestList.length; i++) { text +=

我正在尝试从“for循环”添加属性名和值。但是,它在对象情况下不起作用。但如果我使用HTML表单,它就可以正常工作

    var interestListsObj = {}
    interestLoop:function(interestList){
                var text = "";
                for(var i=0; i<interestList.length; i++) {
                    text += "<option value='"+interestList[i].machine_name+"'>"+ interestList[i].name + "</option>";
    /*line no 6*/   interestListsObj.interestList[i].machine_name =  interestList[i].name;  
                }
                $("#listOfInterest").html(text);    

                console.log(interestListsObj)                   

    },
var interestListsObj={}
interestLoop:函数(interestList){
var text=“”;

对于(var i=0;i问题在于您在
interestListsObj
对象。
如果要使用变量或表达式在对象上创建/访问属性,请使用
[]
方括号表示法。当属性名称为简单javascript标识符时,请使用

将代码更改为:

interestListsObj[interestList[i].machine_name] =  interestList[i].name;

你能告诉我们什么是
interestList
吗?你现在有什么错误吗?使用
[]
符号来创建和访问动态属性。
在这里不起作用。将
interestListsObj.interestList[i]更改为
machine\u name
interestListsObj[interestList[i]。machine\u name]
如果要创建对象,您必须在第6行之前声明interestListsObj.interestList[i]={};是否可以在第6行中解释您到底想做什么注意:interestListsObj您的对象是空的,因此您无法阅读空的道具object@ScottMarcus我的意思是他想用
interestList[I].machine\u name
作为其对象的键。他必须使用
兴趣列表[i].machine\u name]
为此,
不起作用。谢谢你的回答。它很好。我会记住,对于动态属性,我们需要“[]”括号。@Santosh很高兴我帮了忙。:)