javascript数组拆分未定义

时间:2019-04-02 09:24:35

标签: javascript

我正在尝试找出为什么我从函数中得到未定义的错误。它从一开始就可以工作,但是如果我在周围的输入中更改文本“ Text Here”,那将返回未定义?

我今天才开始学习javascript,我不知道为什么,希望有人可以帮助我,我认为我的问题是tagLength吗?

我想做的是使用split和array从一个输入到另一个输入一个接一个地显示文本/单词。

script.container.ui
var tagButton = document.getElementById("buttonTag");
tagButton.addEventListener("click", partyTagChange);

var partTag = null,
  tagLength = 0,
  tagMaxLength = 0;

function partyTagChange() {
  clearInterval(partTag);
  if (partTag !== null) {
    partTag = null;
  } else {
    partTag = setInterval(function() {
      var tag = document.getElementById('inputTag').value;
      var partyNameTag = tag.split(" ")[tagLength];
      document.getElementsByClassName('partyTagInput')[0].value = partyNameTag;
      tagMaxLength = tag.split(" ").length;
      if (tagMaxLength == tagLength + 1) {
        tagLength = 0;
      } else {
        tagLength++;
      }

    }, 500);
  }
}

对不起我的英语不好

2 个答案:

答案 0 :(得分:1)

必须为var arr1 = [["apple"], ["banana", "cherry"]], arr2 = ["id1", "id2"], result = arr1.map((a, i) => a.map(v => [v, arr2[i]].join(' '))); console.log(result);

因为数组中的索引从0开始;

当tagLength =数组长度时,您将在tagMaxLength = tag.split(" ").length-1;中为partyNameTag定义未定义

var partyNameTag = tag.split(" ")[tagLength];
var tagButton = document.getElementById("buttonTag");
tagButton.addEventListener("click", partyTagChange);

var partTag = null,
  tagLength = 0,
  tagMaxLength = 0;

function partyTagChange() {
  clearInterval(partTag);
  if (partTag !== null) {
    partTag = null;
  } else {
    partTag = setInterval(function() {
      var tag = document.getElementById('inputTag').value;
      var partyNameTag = tag.split(" ")[tagLength];
      document.getElementsByClassName('partyTagInput')[0].value = partyNameTag;
      tagMaxLength = tag.split(" ").length-1;
      if (!partyNameTag || tagMaxLength == tagLength) {
        tagLength = 0;
      } else {
        tagLength++;
      }

    }, 500);
  }
}

答案 1 :(得分:0)

只需添加检查tagMaxLength == 1的支票undefined

var tagButton = document.getElementById("buttonTag");
tagButton.addEventListener("click", partyTagChange);

var partTag = null,
  tagLength = 0,
  tagMaxLength = 0;

function partyTagChange() {

  clearInterval(partTag);
  if (partTag !== null) {
    partTag = null;
  } else {
    partTag = setInterval(function() {
      var tag = document.getElementById('inputTag').value;
        var partyNameTag = tag.split(" ")[tagLength];
        document.getElementsByClassName('partyTagInput')[0].value = partyNameTag;
        tagMaxLength = tag.split(" ").length;
        if (tagMaxLength == 1 || tagMaxLength == tagLength + 1) {
          tagLength = 0;
        } else {
          tagLength++;
        }

    }, 500);
  }
}
<input type="text" class="partyTagInput" maxlength="49" value="">
<br>
<input type="text" id="inputTag" maxlength="35" value="TEXT HERE">
<br>
<button id="buttonTag" style="width: 30%;">BUTTON</button>