在JavaScript

时间:2019-02-04 14:04:51

标签: javascript

  

您可以在代码段中看到一系列的范围。当用户   从下拉列表中选择某个号码,我要从中删除该号码   范围并返回新范围

     

一切都按我的预期进行,但我认为我已经结束了   在我的代码中编码并使用了太多if else条语句。我曾是   想知道是否还有更好的方法?

     

如果是,请告诉我,如果Javascript有任何方法可以做到这一点   简单并减少代码量。

var ranges = [
  {start: 1, end: 100},
  {start: 150, end: 300},
  {start: 400, end: 500},
  {start: 550, end: 650},
];


function onSelect(event) {
  let newRange = [];
  let HMID = parseInt(document.getElementById("mySelect").value);
  
  
  for (let range of ranges) {
      
      if ((HMID > range.start) && (HMID < range.end)) {

          newRange.push({start: range.start, end: (HMID - 1)});
          newRange.push({start: (HMID + 1), end: range.end});
      } else if (HMID === range.start) {

          newRange.push({start: (range.start + 1), end: range.end});
      } else if (HMID === range.end) {

          newRange.push({start: range.start, end: (range.end - 1)});
      } else {

          newRange.push(range);
      }
  }
  console.log(JSON.stringify(newRange));
  
}

function onSelectAdd() {

  let newRange = [];
  let HMID = parseInt(document.getElementById("mySelectAdd").value);
  
  
  for (let i = 0; i < (ranges.length); i++) {

  let start, end;

  if (HMID == (ranges[i].start -1)) {
      start = HMID;
      end = ranges[i].end;

      newRange.push({start: start, end: end});
  } else if (HMID == (ranges[i].end + 1)) {
      start = ranges[i].start;

      if (ranges.length === (i + 1)) {
          end = HMID;
      } else {

          if (HMID == (ranges[i+1].start - 1)) {
              end = ranges[i+1].end;
              i++;

          } else {
              end = ranges[i].end;
          }
      }

      newRange.push({start: start, end: end});

  } else {
      newRange.push({start: ranges[i].start, end: ranges[i].end});
  }

  }
  
  console.log(JSON.stringify(newRange));
}
<p>Remove item</p>
<select id="mySelect" onchange="onSelect()">
  <option value="1">1</option>
  <option value="150">150</option>
  <option value="450">450</option>
  <option value="650">650</option>
</select>

<p>Add removed item</p>
<select id="mySelectAdd" onchange="onSelectAdd()">
  <option value="1">1</option>
  <option value="150">150</option>
  <option value="450">450</option>
  <option value="650">650</option>
</select>

1 个答案:

答案 0 :(得分:0)

使用StructuredActivityNode,否则该代码就可以使用。