从带有条件的数组中删除字符串

removing strings from array with conditions

本文关键字:删除 字符串 数组 有条件      更新时间:2023-09-26

我正在尝试用javascript编写函数以从数组中删除字符串。数组是动态创建的,我不时向其添加新字符串。当我从中删除字符串时,我首先检查字符串是否真的在其中。

我还有一个附加条件。如果要删除的字符串等于"自行车",那么我还想检查"摩托车",如果存在,也将其删除。如果给出的字符串是"摩托车",我想删除"自行车"的可能出现。

到目前为止,我有这样的东西:

options_array = []
function remove_option(option) {
  var option_index = options_array.indexOf(option);
  if(option_index != -1)
    options_array.splice(option_index, 1);
  if(option == 'bicycle') {
    option_index = options_array.indexOf('motorbike');
    if(option_index != -1)
      options_array.splice(option_index, 1);
  } else if(option == 'motorbike') {
    option_index = options_array.indexOf('bicycle');
    if(option_index != -1)
      options_array.splice(option_index, 1);
  }
}

它可以工作,但是否有可能让它更好、更干燥?

请参阅 Mozilla 开发者网络上的 Array.prototype.filter 参考

请注意,Array.filter需要一个 ECMAScript 第 5 版编译环境。

实现示例

1. 重申options_array价值

var options_array = [ 'foo', 'bar', 'baz', 'bicycle', 'motorbike' ];
options_array = options_array.filter(function(value){
  return value == 'bicycle';
});
// options_array is now [ 'foo', 'bar', 'baz', 'motorbike' ]

2. 可重用函数与示例 #1 相同

var options_array = [ 'foo', 'bar', 'baz', 'bicycle', 'motorbike' ];
function remove_option( option_name ){
  options_array = options_array.filter(function(value){
    return value == 'bicycle';
  });
}
remove_option( 'bicycle' );
// options_array is now [ 'foo', 'bar', 'baz', 'motorbike' ]
remove_option( 'foo' );
// options_array is now [ 'bar', 'baz', 'motorbike' ]

3. 可重用函数与示例 #2 相同,但适用于任何数组

var options_array = [ 'foo', 'bar', 'baz', 'bicycle', 'motorbike' ];
var options_array2 = [ 'foo', 'bar', 'baz' ];
function remove_option( options_array, option_name ){
  options_array = options_array.filter(function(value){
    return value == 'bicycle';
  });
}
remove_option( options_array, 'bicycle' );
// options_array is now [ 'foo', 'bar', 'baz', 'motorbike' ]
remove_option( options_array2, 'foo' );
// options_array2 is now [ 'bar', 'baz', 'bicycle', 'motorbike' ]

如果需要,您甚至可以构建一个对象原型来管理选项数组,但我认为这些示例就足够了。

尝试

options_array = []
//this can be enhanced to support multiple elements like 'motorbike, tricycle'
var related = {
    'bicycle': 'motorbike',
    'motorbike': 'bicycle'
}
function remove_option(option) {
    remove_opts(option)
    var relation = related[option];
    if (relation) {
        remove_opts(relation)
    }
}
function remove_opts(option){
    var option_index = options_array.indexOf(option);
    if (option_index != -1) options_array.splice(option_index, 1);
}

如何为每个单词使用一个同义词数组:

var synonyms = [
    ['bicycle', 'motorbike'],
    ['car', 'van']
];

然后你可以用一个辅助函数获取匹配列表:

//this will return an array of related words (e.g. ['bicycle', 'motorbike'])
function getSynonyms(item) {
    for (var i = 0; i < synonyms.length; i++) {
        var arr = synonyms[i];
        for (var j = 0; j < arr.length; j++) {
            if (arr[j] == item) return arr;
        }
    }
    return null;
}

最后,您的删除功能可以像这样更改:

//this will remove the option plus any matching synonym words
function remove_option(option) {
    var synonymsToRemove = getSynonyms(option);
    //check if any matches found, if not then just used the single specified option
    if (!synonymsToRemove) synonymsToRemove = [option];
    for (var i = 0; i < synonymsToRemove.length; i++) {
        var option_index = options_array.indexOf(synonymsToRemove[i]);
        if (option_index != -1) {
            options_array.splice(option_index, 1);
        }
    }
}

你可以这样使用:

console.log(options_array);//["bicycle", "motorbike", "car", "van"]
remove_option('bicycle');//remove 'bicycle' and related words (i.e. 'motorbike')
console.log(options_array);//["car", "van"]

这是一个工作示例

您可以使用数组并为其添加别名并循环访问它们

var options_array = ["motorbike",'bicycle','bike','car','vanagon'];
function remove_option(option,alias_array) {
    var option_index = options_array.indexOf(option);
    if(option_index != -1){
        if(alias_array.indexOf(option) != -1){
            for (var i=0;i<alias_array.length;i++){ 
                alias_index = options_array.indexOf(alias_array[i]);
                if(alias_index != -1){
                    options_array.splice(alias_index, 1);
                }   
            }
        }
    }
    return options_array;
}
console.log(remove_option('bike',['motorbike','bicycle','bike']));