修剪数组中的JS [英] trim Array in JS

查看:125
本文介绍了修剪数组中的JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组说

['(','C','1','2',')']

现在我要修剪从阵列从的indexOf('C')开始的数据+ 2 ,如果是数字我需要从数组中删除它。所以对于上述例子最终阵列具有为

Now I want to trim data from array beginning from indexOf('C') + 2 ,If it is a digit I need to remove it from array.. So for the above example final array has to be

 ['(','C','1',')']

例如,如果我有 ['(','C','1','2','3','*',')'] 我希望它被修剪到 ['(','C','1','*',')'] ,元素'C'之后只有一个数字是允许的。

For example if I have ['(','C','1','2','3','*',')'] I want it to be trimmed to ['(','C','1','*',')'] , After element 'C' only one numeral is allowed.

我知道我可以通过获取的indexOf('C'),然后检查数字的每个元素遍历数组..但帮助我做一些高效,更好的办法。喜欢用剪接或东西。

I know I can traverse the array by getting the indexOf('C') and then checking each element for numeric.. but help me with some efficient and better way. like using splice or something.

推荐答案

如果从要微调是已知的位置,你可以使用过滤器在这里,这样的:

If the position from where you want to 'trim' is known, you could use filter here, like.:

var a = ['(','C','1','2','3','*',')']
        .filter( function(a){
                   this.x += 1; 
                   return this.x<=2 ? a : isNaN(+a);}, {x:-1} 
         );

这可能导致本阵列扩展:

Array.prototype.trimNumbersFrom = function(n){ 
    return this.filter( function(a){
                         this.x += 1; 
                         return this.x<=n ? a : isNaN(+a);
                        }, {x:-1} 
           );
};
//=> usage
var a = ['(','C','1','2','3','*',')'].trimNumbersFrom(2);
    //=> ["(", "C", "1", "*", ")"]

另请查看......

这篇关于修剪数组中的JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆