gpt4 book ai didi

javascript - 从循环中添加对象属性不起作用

转载 作者:行者123 更新时间:2023-11-30 15:18:10 25 4
gpt4 key购买 nike

我正在尝试从“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)

},

在上面的代码中,如果我删除“第 6 行”,它就可以正常工作。但不确定第 6 行有什么问题。循环自动退出,没有预期的结果。

最佳答案

问题在于您对 interestListsObj 的属性分配方式 对象。
如果您想使用变量或表达式来创建/访问对象的属性,请使用 [] 方括号表示法。当您的属性名称是简单的 javascript 标识符时,请使用 .

将您的代码更改为:

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

关于javascript - 从循环中添加对象属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44185990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com