通过 Web 表单输入时操作存储在数组中的数据

Manipulating data stored in an array when input via a web form

我正在尝试处理通过 Web 表单输入时以字符串形式存储在数组中的数据。我得到不一致的结果,我不确定为什么。当我通过 'for loop,' 将数据告诉 console.log 时它有效,但是当我尝试 console.log 数组中的特定索引时,我得到“未定义”。

HTML和Javascript如下:

HTML

<head>

</head>    
<body>

    <form id="form">
        <label for="html_input">Input Your HTML</label>
        <input type="text" id="html_input" name="html_input">
        <button type="submit">Submit HTML</button>
    </form>
    <p id="output"></p>
    
    
    <script src=sample.js></script>

</body>

JS

const tag_array = [];


function formSubmit(event) {
  const input = document.getElementById("html_input").value;
  tag_array.push(input.split("<"));
  //the below console.log works
  console.log(tag_array);
  //the below is returning undefined
  console.log(`index 1: ${tag_array[1]}`);
  //the below for loop and console.log works
  for (let i = 0; i < tag_array.length; i++) {
    console.log(tag_array[i]);
  };

  log.textContent = input;
  event.preventDefault();
  };



const form = document.getElementById('form');
const log = document.getElementById('output');
form.addEventListener('submit', formSubmit);

我粘贴到提交表单中试图操纵的内容:

<body margin="0" border="0" style="color:#555555; font-family: Arial, 
  Helvetica, sans-serif; font-size: .7em;">
    
<!---- PRE-HEADER ------>
<p id="preheader" style="display: none; color:#FFFFFF; font-size:1px;">Proud American deals just for you! Today only, take up to  off Vera Bradley Military Collection handbags, 20 percent off Columbia PFG Fishing USA Flag caps, USA and military flags and more, all at shopmyexchange.com and in select stores. Shop now!</p>
<!---- /PRE-HEADER ------>
    
<!-- Email Wrapper Table -->
    
<table align="center" width="600" cellpadding="0" cellspacing="0" border="0" margin="0" style="-webkit-text-size-adjust:100%; -ms-text-size-adjust:100%;">```
    


您的代码中有一个错误:tag_array 只有一个元素,即字符串段数组。

你不需要使用.push(),你应该只分配给数组:

const input = 'tag1<tag2<tag3';
const tag_array = input.split('<');

console.log(tag_array);
// ['tag1', 'tag2', 'tag3']

for (let i = 0; i < tag_array.length; i++) {
  console.log(tag_array[i]);
  // 'tag1', ...
};

看来你要找的是spread operator

缺少:tag_array.push(input.split("<"));
替换为:tag_array.push(...input.split("<"));
因为数组推送不接受数组值作为参数。

完整代码 (ES6)

const myForm    = document.getElementById('my-form')
  ,   myLog     = document.getElementById('my-log')
  ,   tag_array = []

myForm.onsubmit=e=>
  {
  e.preventDefault()
  tag_array.push(...myForm.html_input.value.split('<'))
  myLog.textContent = myForm.html_input.value
  myForm.html_input.value = ''
  
  console.clear()
  tag_array.forEach((elm,i)=> console.log(`index ${i}: ${elm}`))
  }
<form id="my-form">
  <label >Input Your HTML</label>
  <input type="text" name="html_input">
  <button type="submit">Submit HTML</button>
</form>
<p id="my-log"></p>