我有一个数字数组,我想获得第一个小于特定 x 的数字,然后是第一个大于相同 x 的数字。
var str = 'some random string that is kind of long',
items = [],
position = 10, //varies
itemsBefore,
itemsAfter,
firstItemBeforePosition,
firstItemAfterPosition; //varies
for(var i = 0, length= str.length; i < length; i++){
if(str[i] === ' '){
items.push(i);
}
}
itemsBefore = items.filter(function(item){
return item < position;
});
itemsAfter = items.filter(function(item){
return item > position;
});
firstItemBeforePosition = itemsBefore.length > 0 ? itemsBefore[itemsBefore.length - 1] : 0;
firstItemAfterPosition = itemsAfter.length > 0 ? itemsAfter[0] : str.length;
根据我提供的 JavaScript 代码,items 数组将为 [4, 11, 18, 23, 26, 31, 34]
,firstItemBeforePosition
为 4, firstItemAfterPosition
是 11。
有更好的方法吗?
谢谢。
最佳答案
这是另一种方法,它需要较少的代码并且不会循环整个列表。它还使用更少的变量并使用更多的 native 代码函数(应该更快)。
var str, array, length, firstItemBeforePosition, firstItemAfterPosition;
str = 'some random string that is kind of long';
length = 0;
position = 10;
array = str.split(' ');
array = array.map( function( s, i ){ length += s.length; return length+i })
array.some(function(e){
if ( e < position ) firstItemBeforePosition = e;
if ( e > position ) {
firstItemAfterPosition = e;
}
return firstItemAfterPosition;
});
自 1.6 (ES5) 起,some 函数在 Javascript 中可用,并将在 IE9+ 中运行。与 for 循环或 forEach 不同,一旦回调函数返回真值,some 方法就会返回。由于当我们开始时 firstItemAfterPosition
为空,它是假的,有些会继续运行,直到我们为它分配一个值,到时候它会变为真,有些会退出。
如果位置值列表真的很长,我建议查看 binary search因为它将是 O(log n) 而不是 O(n)。如果您不知道这意味着您的问题规模可能足够小,您不必担心 :)
关于javascript - 在一个有序的标量数组中,给定一个数字,找到前面较小的和后面较大的。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19949002/