如何将元素压入并保存在纯Javascript的数组中?

How to push elements and save them in the array in pure Javascript?

搞砸了基础知识。

当我按下回车键或点击按钮时,list 数组的元素发生了变化,而不是附加我写的新元素。

另外,我想 reset<input type='text' maxlength='8' id='aName' placeholder='Write a name.' onKeyDown='enterkey();' />,但没有头绪。

如何修改下面的代码?

function enterkey() {
  if (window.event.keyCode == 13) {
    pushingName();
  }
}

function pushingName(){
  var list=[];
  var oneName = document.getElementById('aName').value;
  var stringName = oneName.toString();

  var nameList = list.push(stringName);

  console.log(list);
}
<input type='text' maxlength='8' id='aName' placeholder='Write a name.' onKeyDown='enterkey();' />
<button onclick='pushingName();'>ADD</button>

您可以尝试下面这个更新后的代码段。

另外如果你需要的话,还有:

  1. 在开头和结尾削减空格所以 ' ss ' => 'ss'

  2. 当字符串为空时什么都不做

  3. 避免数组中出现重复项

  4. 添加后重置输入值。 (在尝试添加副本时不会重置)

  5. 使用另一个按钮删除

let list = [];


function enterkey() {
  if (window.event.keyCode == 13) {
    pushingName();
  }
}

function pushingName(){

  var elName = document.getElementById('aName');
  var stringName = elName.value.toString();
  
  // trimming string if you need it
  stringName = stringName.trim();
  
  if (!stringName.length) {
    return; // check ot mpty string if you need it
  }

  if (list.indexOf(stringName) === -1) { // avoid duplications if you need it
    var nameList = list.push(stringName);
    
    elName.value = ''; // reset value to empty if was added
  }
  
  console.log(list);
}

function removeName(){

  var oneName = document.getElementById('aName').value;
  var stringName = oneName.toString();
  
  // trimming string if you need it
  stringName = stringName.trim();
  
  if (!stringName.length) {
    return; // check ot mpty string if you need it
  }

  // filtering our stringName
  list = list.filter(item => item !== stringName);

  
  console.log(list);
}
<input type='text' maxlength='8' id='aName' placeholder='Write a name.' onKeyDown='enterkey();' />
<button onclick='pushingName();'>ADD</button>
<button onclick='removeName();'>REMOVE</button>