javascript从数组中删除项目,如果项目已存在于数组中 [英] javascript remove item from array, if an item already existing in array
问题描述
以下项目添加到数组:
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')
- APPLE
should be added to array.
如果我再次致电
AddToFilterOptionList('APPLE + FRUIT')
- 它应该从数组 arrayOptions
中删除项目 APPLE 并添加 APPLE + FRUIT
AddToFilterOptionList('APPLE+FRUIT')
- it should remove the the item 'APPLE' from array arrayOptions
and should add APPLE+FRUIT
任何时候只有一个以 APPLE
开头的单词可以在数组中。
如何在javascript中找到喜欢'APPLE'这个词。
Any time only one word that starts with APPLE
can be in array.
How to find the word like 'APPLE' in javascript.
我试过匹配()
返回匹配的单词。 IndexOf()
仅在整个单词匹配但不是单词开头时返回1.
I tried with Match()
which returns the matching word. IndexOf()
returns 1 only if whole word is match but not start of word.
推荐答案
遍历数组,然后使用startsWith方法。
Cycle through the Array and then use the startsWith method.
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从数组中删除项目,如果项目已存在于数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!