简体   繁体   English

如何只删除一次数组元素以使用 for 循环添加新元素

[英]How can I delete array elements just once to add new ones with a for loop

What I am trying to do is:我想做的是:

  1. set an array value (list) to another array (options).将数组值(列表)设置为另一个数组(选项)。
  2. If the user's input (searchVal) matches with a list value it will delete options, push this match, and then will keep pushing the next matches without deleting options again.如果用户的输入 (searchVal) 与列表值匹配,它将删除选项,推送此匹配项,然后继续推送下一个匹配项而不再次删除选项。

So according to the code below, if searchVal was "whatever" , options should return: ["whatever", "whatevEver1"] but, instead, it returns: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]所以根据下面的代码,如果 searchVal 是"whatever" ,选项应该返回: ["whatever", "whatevEver1"]但是,相反,它返回: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]

Relevant code:相关代码:

var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
    
    
for (var i=0 ; i < list.length ; i++)
{
    options.push([list[i]]);
}
    
var searchVal = window.prompt(" ");
     
for (var i=0 ; i < list.length ; i++)
{
    if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
        if (clear == 0) {
            options.length = 0; 
        }
        options.push([list[i]]);
    }
    clear++;
}

return options;

Js arrays are pass-by-reference. Js arrays 是通过引用传递的。 In order to make independent copy of array you need to use:为了制作数组的独立副本,您需要使用:

let options = JSON.parse(JSON.stringify(list));

I didnt try to implement this to your problem cause im too lazy but i think it might work.我没有尝试对您的问题实施此操作,因为我太懒了,但我认为它可能会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 JavaScript 中的数组开头添加新的数组元素? - How can I add new array elements at the beginning of an array in JavaScript? 如何向 JavaScript 中的现有键值添加新键值? - How can I add new key values to existing ones in JavaScript? 我如何一次只对一个数组元素设置状态? - How can I setState on just one array element at once? 如何在React中动态地在一些现有元素之间添加新元素? - How do I add new elements in between some existing ones dynamically in React? 如何将新元素添加到列表中? - How can I add new elements to a list? 如何将元素添加到数组,然后将数组的新值添加到localStorage? - How can i add elements to an array and then add the arrays new value to localStorage? 如何遍历表单中的元素以检查哪些元素被触摸? - How can I loop through the elements on my form to check which ones were touched? 如何一次在两个数组元素上设置状态? - How can I setState on two array elements at once? 我如何在保留非数字元素值的同时在数组中划分数字元素 - how can i divide numeric elements in an array while keeping the values of non-numeric ones 反应映射复选框重复返回所有数组元素,而不只是我检查过的那些 - React mapped checkbox repeating back all of the array elements, instead of just the ones i've checked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM