Javascript 使用用户输入从数组中删除元素
我在从Javascript数组中删除项时遇到问题。我使用的是一个提示,当用户输入一个工作者的ID号时,我希望该元素从数组中删除 目前,我的代码只会删除列表中的最后一个元素 这是我的代码:Javascript 使用用户输入从数组中删除元素,javascript,Javascript,我在从Javascript数组中删除项时遇到问题。我使用的是一个提示,当用户输入一个工作者的ID号时,我希望该元素从数组中删除 目前,我的代码只会删除列表中的最后一个元素 这是我的代码: var remove = function(){ var removeID = prompt("Enter ID of the worker you wish to remove: "); var index = array.indexOf(removeID); if(removeID
var remove = function(){
var removeID = prompt("Enter ID of the worker you wish to remove: ");
var index = array.indexOf(removeID);
if(removeID == id){
array.splice(index, 1);
showArray();
}
else{
alert("id is not in the system");
}
}
我想你把逻辑搞乱了
if(removeID == id){
在删除该id之前,可能应该检查该id是否存在于数组中
if(index !== -1){
还有一个猜测,因为您没有给出一个可运行的示例:
var removeID = Number(prompt("Enter ID of the worker you wish to remove: "));
你把数组索引和元素混在一起了。应该是这样的:
var remove = function(){
var removeID = prompt("Enter ID of the worker you wish to remove: ");
var index = array.indexOf(removeID);
if(index > -1){ // HERE!!!
array.splice(index, 1);
showArray();
}
else{
alert("id is not in the system");
}
}
var removeID = parseInt(prompt("Enter ID of the worker you wish to remove: "));
另外两项意见:
- 如果ID是数字,那么对array.indexOf()的调用将始终返回-1。prompt()将始终为您提供字符串,而不是整数;您应该像这样使用parseInt():
var remove = function(){ var removeID = prompt("Enter ID of the worker you wish to remove: "); var index = array.indexOf(removeID); if(index > -1){ // HERE!!! array.splice(index, 1); showArray(); } else{ alert("id is not in the system"); } }
var removeID = parseInt(prompt("Enter ID of the worker you wish to remove: "));
- 由于ID是唯一的,并且取决于上下文,因此将它们存储在对象中而不是数组中可能是有意义的,这样您就不会有重复ID的风险
var array = ['one','two','three',4,5,6,7,8,9,10];
var remove = function(removeID){
var index = array.indexOf(removeID);
if (index>-1) {
array.splice(index, 1);
}
}
remove(prompt("Enter ID of the worker you wish to remove: "));
console.log(array);
if(removeID==id){
没有意义这是工作者的id,它已经在Javascript的其余部分声明了,这一切都工作得很好。所以你说如果他们输入的id只与该工作者匹配,那么他们就可以删除它……将if(removeID==id){
更改为if(index>=0){
它将按照您期望的方式工作。我已经尝试过了,但是当我尝试时,它根本不会删除任何内容。那么indexOf是否真的找到了输入的ID?实际数组中是什么?是字符串还是数字?我刚刚更新了我的上述答案。我想问题可能是您有整数ID,而prompt()是始终返回字符串。如果数组为[1,2,3],则array.indexOf(1)==0,但array.indexOf('1')==1。