扩展slice为数组中包含字符串'NN'的第一个元素

expand slice to be from first element in array that contains string 'NN'

本文关键字:NN 元素 第一个 字符串 slice 数组 包含 扩展      更新时间:2023-09-26

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

如果数组有一个包含NN的单词,然后有一个包含IN的单词,我如何使起始值成为包含NN的第一个单词。则最终值将与正常值一样,即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"];

你已经完成了大部分工作-

一旦你找到了第一个"IN",就回去看看在它之前是否有一个"NN"——如果有的话,更新"first"来指向它。

但是你不需要所有这些复杂的reduce代码-你可以使用数组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(' ')

edit: lastIndexOf不支持IE8及以下版本-如果你想支持IE7-IE8,你可以在列表切片代码运行之前添加此填充代码一次:

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