gpt4 book ai didi

javascript从数组中删除项目,如果一个项目已经存在于数组中

转载 作者:行者123 更新时间:2023-11-30 08:37:03 26 4
gpt4 key购买 nike

以下将项目添加到数组:

var arrayOptions = [];

function AddToFilterOptionList(mode) {
arrayOptions.push(mode);
}

从数组中删除项目:

function RemoveFromFilterOptionList(mode) {
var index = arrayOptions.indexOf(mode);
if (index !== -1) {
arrayOptions.splice(index, 1);
}}

例如如果我打电话

AddToFilterOptionList('APPLE') - APPLE 应该添加到数组中。

如果我再打电话

AddToFilterOptionList('APPLE+FRUIT') - 它应该从数组 arrayOptions 中删除项目“APPLE”并且应该添加 苹果+水果

任何时候数组中只能包含一个以APPLE 开头的单词。如何在 javascript 中找到 like 'APPLE' 这个词。

我尝试使用 Match() 返回匹配的词。 IndexOf() 仅当整个单词匹配但不是单词开头时才返回 1。

最佳答案

循环遍历数组,然后使用 startsWith 方法。

void AddToFilterOptionList(String mode) {
for (i=0; i<arrayOptions.length; i++) {
if (mode.startsWith(arrayOptions[i] == 1)) {
array[i] = mode;
return; // found, so return
}
}
arrayOptions.push(mode); // should only get here if string did not exist.
}

关于javascript从数组中删除项目,如果一个项目已经存在于数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com