分割不同长度的字符串值并将这些值分配给对象

时间:2018-08-19 19:01:27

标签: javascript arrays function object for-loop

标签中有多个长度不同的字符串值,其中包含一个复选框,如下所示:

<label>
  <input type="checkbox" name="standard-length">Course Title - Monday 9pm-12pm, $100
</label>
<label>
  <input type="checkbox" name="different-length">Different Length Title - Tuesday 12pm-2am, $200
</label>
<label>
  <input type="checkbox" name="everything">All - $400
</label>

我想做的是遍历这些字符串,切出标题,时间段和价格,并将它们存储在一个对象中。首先,我必须从标签的textContent中使用.trim()空格,然后尝试使用.split()和.slice()来获取字符串的每个片段,但是由于标题是不同的长度,并且有一个标签完全错过了时间。思考过程是这样的:

let getStrDetails(str) => {
  const strDetails = {
    checkbox: '',
    title: '',
    day: '',
    time: '',
    price: ''
};
for (prop in strDetails) {
  // Check if the checkbox is checked, assign boolean true/false
  // Get the title and assign it to the title value in the object
  // Get the day and assign it to the day value in the object
  // Get the time...
  // Get the price, remove the $ and turn it into an integer for maths when calculating the totals (tried strDetails["price"] = str.slice(-3);

}
return str;
}

我认为获取价格很容易,因为它们在3位数字和字符串末尾都具有相同的长度,所以.slice(-3)可以工作。但是标题的长度不同,因此我尝试使用破折号(“-”)作为结束索引,并且由于每个标题都以空格开头,因此我尝试通过indexOf(1)访问它来使用该空格,因为从技术上讲,第一个字母位于空格之后,而第二个字符位于数组之后。然后,我尝试使用“,”作为索引的结尾,因为它在时间之后落入,等等。

我将所有这些都绑定到一个事件处理程序,以便在单击复选框时触发逻辑,因为我还比较了相互冲突的日期,并且如果复选框位于同一天和同一时间,则将其禁用。

尽管使用了一个不太好的解决方案,但我使用了一个完全不同的解决方案,但是我试图更好地理解如何为对象分配值并对其进行迭代,并创建以后可以使用的可访问属性,例如:

if(Get str1[time) and compare it to str2[time]) {
  // set str1 checkbox boolean to false and do something to disable it in the html
}

0 个答案:

没有答案