繁体   English   中英

为什么我不能删除数组的元素?

[英]why i can not remove elements of an array?

我想问一下,我有一个数组,我想用阵列中存储的元素消除数组中的一些元素,所以插图如下:

array1 =进程,收集,成熟,庄稼,来自,领域,收割,是,切割array2 =,from,the,is,a,an

如果array1中有元素也是array2的元素。 然后这些元素将被淘汰。

我使用的方法如下:

var array1 = ["of","gathering","mature","crops","from","the","fields","Reaping","is","the","cutting"];
var kata = new Array();
kata[0] = " is ";
kata[1] = " the ";
kata[3] = " of ";
kata[4] = " a ";
kata[5] = " from ";


for(var i=0,regex; i<kata.length; i++){
        var regex = new RegExp(kata[i],"gi");
        array1 = array1.replace(regex," ");
    }

为什么我不能立即消除数组的元素?

我一直在使用这个方法:当我想要消除array1中的一些元素时,数组是我第一次通过以下方式更改为字符串:

var kataptg = array1.join (" ");

但是,如果使用该方法,有几个元素应该丢失,但可能会丢失,因为模式不像上面的数组kata。

假设单词“of” ,数组的模式kata =“of”; 但在模式array1 =“of”;

即使写入模式与数组kata中的写入模式不同,如何删除这些元素?

array1中的项目没有引号,因此JavaScript认为它们是(未定义的)变量。

假设你已经修复了(以及杂散引号),你的下一个问题是你在数组对象上调用replace()。 replace()仅适用于字符串。

# Simplified from
# http://phrogz.net/JS/Classes/ExtendingJavaScriptObjectsAndClasses.html#example5
Array.prototype.subtract=function(a2){ 
   var a1=this;
   for (var i=a1.length-1;i>=0;--i){ 
      for (var j=0,len=a2.length;j<len;j++) if (a2[j]==a1[i]) {
        a1.splice(i,1);
        break;
      } 
   } 
   return a1;
}

var a1 = "process of gathering mature crops from the fields".split(" ");
var a2 = "of from the is a an".split(" ");
a1.subtract(a2);
console.log(a1.join(' '));
// process gathering mature crops fields

如果性能是一个问题,那么显然有更好的方法不是O(m * n),例如将a2的单词推入对象进行恒定时间查找,这样它就是线性时间通过源数组来丢弃忽略的单词,O(m + n):

var a1 = "process of gathering mature crops from the fields".split(" ");
var a2 = "of from the is a an".split(" ");
var ignores = {};
for (var i=a2.length-1;i>=0;--i) ignores[a2[i]] = true;
for (var i=a1.length-1;i>=0;--i) if (ignores[a1[i]]) a1.splice(i,1);
console.log(a1.join(' '));
// process gathering mature crops fields

这是使用正则表达式的另一个解决方案(可能是O(m + n)):

var s1 = "process of gathering mature crops from the fields";
var a2 = "of from the is a an".split(" ");
var re = new RegExp( "\\b(?:"+a2.join("|")+")\\b\\s*", "gi" );
var s2 = s1.replace( re, '' );
console.log( re ); // /\b(?:of|from|the|is|a|an)\b/gi
console.log( s2 ); // "process gathering mature crops fields"

您可以将所有'丢弃'放在一个reg exp中,并测试每个数组项中的任何一个。

通过从数组的末尾开始,您可以在向阵列的开头前进行拼接。

var array1= ['of','gathering','mature','crops','from','the','fields',
'Reaping','is','the','cutting'],
kata= ['is','the','of','a','from'], L= array1.length,
rx= RegExp('^('+kata.join('|')+')$','i');

while(L){
    if(rx.test(array1[--L])) array1.splice(L, 1);
}

alert(array1)

/ *返回值:(数组)['收集','成熟','作物','字段','收割','切割'] * /

(这里的rx是= / ^(是| | | |来自)$ / i)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM