如何从数组中的数字之前/之后获取值?

时间:2015-10-12 09:42:52

标签: javascript

我的范围是1000 - 1200

我想排除数字1002,1030和1040并获取它们之前和之后的范围:

1000 - 1001
1003 - 1029
1031 - 1039
1041 - 1200

我现在有了这个,我可以输入数字并重新获得数组。

对于第二部分,我使用jQuery插件,但我认为我需要做一些其他事情才能将数组作为参数传递。

此外,我不知道如何在exclusion之前和之后获取范围

function range(first, second) {
    list = []
    this.first = first;
    this.second = second;
    for (var i = first; i <= second; i++) {
        list.push(i)
    }
    return list;
}
a = new range(1, 5)
console.log(a + " this is the original list")

exclusion = 3 //should be a array

listExcluded = jQuery.grep(list, function (value) {
    return value != exclusion;
});

console.log(listExcluded + " this is value without excluded number")

2 个答案:

答案 0 :(得分:1)

这是一个简单的样本......可能由js专家优化。

&#13;
&#13;
function range(first, second) {
    this.list = []
    this.first = first;
    this.second = second;
    for (var i = first; i <= second; i++) {
        this.list.push(i)
    }
    return this.list;
}

var a = new range(1, 10)

console.log(a + " this is the original list")

var ec = [3,6];  // should be a array

var b = [];      // new array holding the sliced arrays
var start = 0;

for (var i = 0; i <= ec.length; i++) {
  
  if (i == ec.length) {  
    b.push(a.slice(start))
    
  } else {  
    b.push(a.slice(start,ec[i]-1))
    start = ec[i];

  }
      
}

for (var i = 0; i < b.length; i++) {
  console.log("Array nr:" + (i+1) + ": " + b[i])
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你需要的是一种算法,不是Javascript特有的,也不是JQuery。 尝试类似的东西:

var initialList = range(1000, 1200);
var exclusions = [1002, 1030, 1040];

var result = [];
var currentSubList = [];
initialRange.forEach(function (v) {
    if (exclusions.indexOf(v) > -1) {
        if (currentSubList.length > 0) {
            result.push(currentSubList);
            currentSubList = [];
        }
    } else {
        currentSubList.push(v);
    }
});
if (currentSubList.length > 0) {
    result.push(currentSubList);
}