替换indexOf

时间:2016-08-02 01:35:51

标签: javascript

我编写了这个相对简单的代码,用于在排序数组中找到应该插入值的点。

function findInsertionIndex(array, value){
    var i = 0
    while(array[i]){
        if(value<array[i].value) break
        i++
    }
    return i
}

这段代码效果很好,但我想在数组上用indexOf替换它,以提高可读性和简洁性。我试过这个,其中值在外部范围内:

var insertionIndex = array.findIndex(e=> e.value<value) || 0

有人可以指出缺少的东西吗?

可运行

&#13;
&#13;
function findInsertionIndex(array, value){
  var i = 0
  while(array[i]){
    if(value<array[i].value) break
    i++
  }
  return i
}

// Run the code
a = [{value:1},
     {value:5},
     {value:6},
     {value:7},
     {value:9},
     {value:23},
     {value:84}]
ind = findInsertionIndex(a, 15)
console.log(ind)

////////
// Try with indexOf
////////
a = []
value = 15

// Add a first item
ind = a.findIndex(e=> e.value<value)
ind = ind>0 ? ind : 0
a.splice(ind, 0, 3)

// Add a second item
ind = a.findIndex(e=> e.value<value)
ind = ind>0 ? ind : 0
a.splice(ind, 0, 5)

// Add a third item
ind = a.findIndex(e=> e.value<value)
ind = ind>0 ? ind : 0
a.splice(ind, 0, 4)



console.log(a)
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

那么,findIndex方法到底是什么?

  

如果数组中的元素满足提供的测试函数,则findIndex()方法返回数组中的索引。否则返回-1。

由于您检查数组值是否小于测试值(e.value < value),因此它始终是第一个索引(即0)返回的内容。

为了得到你想要的东西,你必须颠倒这样的逻辑:e.value > value,然后它与你的while循环相当。

您的索引分配(ind)也需要更改,因为现在没有找到的含义是数组中没有更小的元素(即值是最大的元素):

ind = ind >= 0 ? ind : a.length

也许看看这个小提琴:https://jsfiddle.net/cLqf6vg8/

我不知道这对你来说是否是一个重要的问题,但你也可以考虑如果价值相等会发生什么。是应该在之前还是之后插入。如果您在使用前需要>=,则为>

但正如一些评论员所说,如果您的阵列已排序,那么有一些更好更快的算法,例如二进制搜索(也很容易实现)。 / p>

答案 1 :(得分:0)

是因为<需要逆转吗?

value<array[i].value

VS

e.value<value