【发布时间】:2018-06-07 20:56:33
【问题描述】:
想象一个由用户操作创建、填充和更改的对象。创建零件是我遇到问题的时候;)。除非我事先为对象准备好键,否则 JS 不会分配属性,因为键尚未物理创建。
dataObj.run1是事先准备好的,所以function saveSelection();填写没有问题。
当我递增到下一次运行时(使用function goNext();)- run2 没有被填充,因为它不存在。
怎么办?基于构造函数创建新对象并继续推送它?还有其他想法吗?
我的代码:
var dataObj = {
run1 : {
sel1 : {
id : "",
text : ""
},
sel2 : {
id : "",
text : ""
}
},
run2 : {
// how to fill it in automatically...
}
};
var realCount = 1;
var runCount = "run1"; // any preetier version of the incremeant here - see function goNext();?
function saveSelection(that) {
var selectId = that.id;
var selectedOptionId = that.selectedIndex;
var selectedOptionText = that.selectedOptions[0].text;
dataObj[runCount][selectId].id = selectedOptionId;
dataObj[runCount][selectId].text = selectedOptionText;
console.log(dataObj);
};
function goNext () {
// Reset selections:
document.getElementsByClassName("select")[0].selectedIndex = 0;
document.getElementsByClassName("select")[1].selectedIndex = 0;
// Increase count:
realCount++;
var runCountTemp = runCount.slice(0,3);
runCount = runCountTemp + realCount;
console.log(runCount);
};
<div id="app">
<select class="select" name="city" id="sel1" onchange="saveSelection(this);">
<option value="0">London</option>
<option value="1">New York</option>
<option value="2">San Francisco</option>
</select>
<select class="select" name="color" id="sel2" onchange="saveSelection(this);">
<option value="0">Blue</option>
<option value="1">Red</option>
<option value="2">Green</option>
</select>
<!-- Commented out as immaterial to this question
<button onclick="goBack();" class="buttonBack">BACK</button>
-->
<button onclick="goNext();" class="buttonNext">NEXT</button>
</div>
【问题讨论】:
标签: javascript arrays object