将切片扩展为包含字符串' NN'的数组中的第一个元素。

时间:2014-06-19 20:55:52

标签: javascript arrays

我有这个代码从起始值得到一个数组的拼接,它被计算为包含IN的第一个单词,然后计算到结束值,该结束值被计算为包含NN的最后一个单词。 / p>

如果数组包含一个包含NN的单词,那么如何将起始值作为包含NN的第一个单词,然后在包含N的单词后面。然后结束值将正常,即NN的最后一个实例。

var first = theTopic.split(' ').reduce(function(p, c, i){
    return p != -1 ? p : c.indexOf('IN') != -1 ? i : -1;
}, -1);
var last = theTopic.split(' ').reduce(function(p, c, i, a){
    return c.indexOf('NN') != -1 ? i : p;
}, -1);
if(theTopic.indexOf('IN') > -1){
    lastLocation = (theTopic.split(' ').slice(first, last + 1)).join(' ').replace(/,|\(.*?\)/g, ''));
}

目前,如果数组如下:["PB", "IN", "NN"],则lastLocation设置为[" IN"," NN"]。目前,如果数组如下:["LL", "XC", "NN", "IN", "NN"],则lastLocation将设置为[" IN"," NN"]。

我想要的是,如果有一个" NN"然后是" IN",例如在["LL", "XC", "NN", "IN", "NN"]中,则lastLocation设置为["NN", "IN", "NN"];

1 个答案:

答案 0 :(得分:0)

你已完成大部分工作 -

一旦你找到了第一个“IN”,就回去查看之前是否有“NN” - 如果有更新“第一个”指向它。

但是你不需要所有这些复杂的减少代码 - 你可以先使用数组indexOf,最后使用lastIndexOf

试试这个:

var theTopic = "LL XC NN IN NN";
var tokens = theTopic.split(' ');
var last_index = tokens.lastIndexOf('NN');  // the last NN
var in_index = tokens.indexOf('IN');  // the IN
var first_index = tokens.lastIndexOf('NN', in_index); // search for last 'NN' before last 'IN'
var result = tokens.slice(first_index, last_index+1).join(' ')

编辑:IE8及以下版本不支持lastIndexOf - 如果您需要IE7-IE8支持,可以在列表切片代码运行之前添加此polyfill代码一次:

[].lastIndexOf || (Array.prototype.lastIndexOf = function(a,b){for(++b>0?0:b=this.length+~~b;~--b&&(!(b in this)||this[b]!==a););return b}