如何在数组中找到缺失值的索引?

时间:2021-01-05 21:29:16

I have an array like

我有一个像这样的数组

a=[1,2,3,,4,5];

So now I want to find the missing value index, i.e. 3, using indexOf.

所以现在我想使用indexOf找到缺失值索引,即3。

8 个解决方案

#1


6  

Check if the value is undefined like the following code:

检查值是否未定义,如下面的代码:

for ( var i = 0; i < a.length; i++ ) {
    if ( typeof a[i] === "undefined" ) {
        // do stuff here or break the loop
    }
}

Update You can do this too:

更新您也可以这样做:

Array.prototype.indexOfUndefined =  function() {
    for ( var i = 0; i < this.length; i++ ) {
        if ( typeof this[i] === "undefined" ) {
            return i;
        }
    }
}

You need to return i because i is the current index, it will search for the first undefined value.

您需要返回i,因为我是当前索引,它将搜索第一个未定义的值。

Demo: http://jsfiddle.net/vdyypq6o/5/

演示:http://jsfiddle.net/vdyypq6o/5/

#2


2  

Unfortunately, ES5 Array methods are required* to skip such array holes**, so no indexOf() or forEach() will help. ECMAScript 2015 has two new methods called find() and findIndex() that could help you, but they are not widely supported yet, so I assume it's not a good answer for this question.

不幸的是,ES5 Array方法需要*来跳过这样的数组漏洞**,所以没有indexOf()或forEach()会有所帮助。 ECMAScript 2015有两个名为find()和findIndex()的新方法可以帮到你,但它们还没有被广泛支持,所以我认为这个问题不是一个好的答案。

What's left is a good old iteration over indexes:

剩下的是对索引的一个很好的旧迭代:

function findHole(a) {
    for (var i = 0; i < a.length; i++) {
        // check for only `a[i] === undefined` could be faster,
        // but is not enough as it will cause false positives
        // when array actually contains `undefined` value
        // for example, for `a = [1, undefined, , 2]`,
        // correct implementation should return `2`, not `1`
        if (a[i] === undefined && !a.hasOwnProperty(i)) {
           console.log("Found hole at index " + i);
           return i;
        }
    }
    return -1;
}

* — see step 9 in http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 for indexOf() and step 8 http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19 for map() algorithms that require skipping holes

* - 参见http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.14中的indexOf()和步骤8中的步骤9 http://www.ecma-international.org/ecma -262 / 5.1 /#sec-15.4.4.19用于需要跳过孔的map()算法

** — a hole is created in array when there's no value defined for some index, so technically it's not correct to say that a[3] has null or undefined value, because there just isn't any value. But in JavaScript, when we try to get not defined property of some object, what we get is undefined, that why a[3] === undefined is true.

** - 当没有为某个索引定义值时,在数组中创建一个洞,所以从技术上讲,如果[3]具有空值或未定义值,那是不正确的,因为没有任何值。但是在JavaScript中,当我们尝试获取某个对象的未定义属性时,我们得到的是未定义的,为什么[3] === undefined为真。

#3


0  

a = [1,2,3,,4,5];
i = 0;
$.each(a , (function(){
  if(a[i]=="") {
    alert(i + ":: yes this is null index");
  }
  i++;
});

you can use the each loop for this purpose. May be there are more solutions for this purpose in market :P but this is also a good one. you should try this.

你可以使用每个循环来达到这个目的。可能在市场上有更多的解决方案用于此目的:P但这也是一个很好的解决方案。你应该试试这个。

#4


0  

Just adding another way to achieve what you need -

只需添加另一种方法来实现您的需求 -

for ( var i = 0; i < a.length; i++ ) {
    if (!a[i]) {
      console.log("Null index = ",i);
    }
}

#5


0  

You can try this

你可以试试这个

                  a=['1','2','3',,'4']
            
            for(var i=0;i<a.length;i++)
              {
               if( a.indexOf(a[i])==-1)
                 // if(typeof a[i] == 'undefined')
                    alert("Index-->"+i)
              }

#6


0  

Yet another way with reduce function, getting all missed values.

还有另一种减少功能的方法,获取所有错过的值。

function findMissed(arr){
    var result = arr.reduce(function(acc,el,index){
        if(index - acc.cur > 1) {
            for(var i=acc.cur+1;i < index;i++){
                acc.res.push(i);
            }
        }
        acc.cur = index;
        return acc;
    },{cur:-1,res:[]});
    var missed = result.res;
    if(result.cur !== arr.length){
      for(var i=result.cur+1;i<arr.length;i++){
          missed.push(i);
      }
    }
    return missed;
}

function findMissed(arr) {
  var result = arr.reduce(function(acc, el, index) {
    if (index - acc.cur > 1) {
      for (var i = acc.cur + 1; i < index; i++) {
        acc.res.push(i);
      }
    }
    acc.cur = index;
    return acc;
  }, {
    cur: -1,
    res: []
  });
  var missed = result.res;
  if (result.cur !== arr.length) {
    for (var i = result.cur + 1; i < arr.length; i++) {
      missed.push(i);
    }
  }
  return missed;
}

var a = [1, 2, 3, , 4, 5];
var missed = findMissed(a);
printRes(a, missed);

console.log(missed)

a = [1, , 3, , 5, , 7, , 9]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);

a = [1, ,,,]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);

a = [,,,]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);

a = [,,,2]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);



function printRes(src, res) {
  document.getElementById('res').innerHTML += JSON.stringify(src) + '<br/>' + JSON.stringify(res) + '<br/>';
}
<div id="res"></div>

#7


0  

Assuming there are two characters that you know aren't in the data (such as a pound sign # and pipe |), you can use this one-liner:

假设您知道有两个字符不在数据中(例如井号#和管道|),您可以使用这个单行:

Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1);

The 9s are simply placeholders in case the missing element is at the beginning or end. (But note that a single extra comma at the end of an array is ignored in JavaScript, so there's no way to check for that condition.)

9s只是占位符,以防缺少的元素在开头或结尾。 (但请注意,在JavaScript中会忽略数组末尾的一个额外逗号,因此无法检查该条件。)

Snippet

片段

console.clear();

//hole at beginning:
a= [,1,2,3,4,5];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //0

//hole in middle:
a= [1,2,3,,4,5];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //3

//an extra comma at the end of an array is ignored in JavaScript:
a= [1,2,3,4,5,];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //-1  

//only the last comma is ignored:
a= [1,2,3,4,5,,];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //5

#8


-1  

Creating an array like so a=[1,2,3,,4,5]; will cause a[3] to be undefined and not null.

像这样创建一个数组a = [1,2,3 ,, 4,5];将导致[3]未定义而不为空。

a.indexOf(undefined) or a.indexOf('undefined') will not work for obvious reason. Setting a[3] to null will not work either since everything that follows will be shifted left.

a.indexOf(未定义)或a.indexOf('undefined')将无法正常工作。将[3]设置为null将不起作用,因为后面的所有内容都将向左移位。

I recommend creating your own array method that will search for every undefined value.

我建议您创建自己的数组方法,以搜索每个未定义的值。

var arr = [1,2,3,,4,5];

Array.prototype.findMissingValues = function(callback){
    for(var i = 0; i < this.length; i++){
        if(typeof this[i] === 'undefined'){

            if(typeof callback != 'undefined'){
                callback.apply(this, [i, this[i]]);
            }
        }
    }
}
arr.findMissingValues(function(index, value){
    alert(value);
});

#1


6  

Check if the value is undefined like the following code:

检查值是否未定义,如下面的代码:

for ( var i = 0; i < a.length; i++ ) {
    if ( typeof a[i] === "undefined" ) {
        // do stuff here or break the loop
    }
}

Update You can do this too:

更新您也可以这样做:

Array.prototype.indexOfUndefined =  function() {
    for ( var i = 0; i < this.length; i++ ) {
        if ( typeof this[i] === "undefined" ) {
            return i;
        }
    }
}

You need to return i because i is the current index, it will search for the first undefined value.

您需要返回i,因为我是当前索引,它将搜索第一个未定义的值。

Demo: http://jsfiddle.net/vdyypq6o/5/

演示:http://jsfiddle.net/vdyypq6o/5/

#2


2  

Unfortunately, ES5 Array methods are required* to skip such array holes**, so no indexOf() or forEach() will help. ECMAScript 2015 has two new methods called find() and findIndex() that could help you, but they are not widely supported yet, so I assume it's not a good answer for this question.

不幸的是,ES5 Array方法需要*来跳过这样的数组漏洞**,所以没有indexOf()或forEach()会有所帮助。 ECMAScript 2015有两个名为find()和findIndex()的新方法可以帮到你,但它们还没有被广泛支持,所以我认为这个问题不是一个好的答案。

What's left is a good old iteration over indexes:

剩下的是对索引的一个很好的旧迭代:

function findHole(a) {
    for (var i = 0; i < a.length; i++) {
        // check for only `a[i] === undefined` could be faster,
        // but is not enough as it will cause false positives
        // when array actually contains `undefined` value
        // for example, for `a = [1, undefined, , 2]`,
        // correct implementation should return `2`, not `1`
        if (a[i] === undefined && !a.hasOwnProperty(i)) {
           console.log("Found hole at index " + i);
           return i;
        }
    }
    return -1;
}

* — see step 9 in http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 for indexOf() and step 8 http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19 for map() algorithms that require skipping holes

* - 参见http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.14中的indexOf()和步骤8中的步骤9 http://www.ecma-international.org/ecma -262 / 5.1 /#sec-15.4.4.19用于需要跳过孔的map()算法

** — a hole is created in array when there's no value defined for some index, so technically it's not correct to say that a[3] has null or undefined value, because there just isn't any value. But in JavaScript, when we try to get not defined property of some object, what we get is undefined, that why a[3] === undefined is true.

** - 当没有为某个索引定义值时,在数组中创建一个洞,所以从技术上讲,如果[3]具有空值或未定义值,那是不正确的,因为没有任何值。但是在JavaScript中,当我们尝试获取某个对象的未定义属性时,我们得到的是未定义的,为什么[3] === undefined为真。

#3


0  

a = [1,2,3,,4,5];
i = 0;
$.each(a , (function(){
  if(a[i]=="") {
    alert(i + ":: yes this is null index");
  }
  i++;
});

you can use the each loop for this purpose. May be there are more solutions for this purpose in market :P but this is also a good one. you should try this.

你可以使用每个循环来达到这个目的。可能在市场上有更多的解决方案用于此目的:P但这也是一个很好的解决方案。你应该试试这个。

#4


0  

Just adding another way to achieve what you need -

只需添加另一种方法来实现您的需求 -

for ( var i = 0; i < a.length; i++ ) {
    if (!a[i]) {
      console.log("Null index = ",i);
    }
}

#5


0  

You can try this

你可以试试这个

                  a=['1','2','3',,'4']
            
            for(var i=0;i<a.length;i++)
              {
               if( a.indexOf(a[i])==-1)
                 // if(typeof a[i] == 'undefined')
                    alert("Index-->"+i)
              }

#6


0  

Yet another way with reduce function, getting all missed values.

还有另一种减少功能的方法,获取所有错过的值。

function findMissed(arr){
    var result = arr.reduce(function(acc,el,index){
        if(index - acc.cur > 1) {
            for(var i=acc.cur+1;i < index;i++){
                acc.res.push(i);
            }
        }
        acc.cur = index;
        return acc;
    },{cur:-1,res:[]});
    var missed = result.res;
    if(result.cur !== arr.length){
      for(var i=result.cur+1;i<arr.length;i++){
          missed.push(i);
      }
    }
    return missed;
}

function findMissed(arr) {
  var result = arr.reduce(function(acc, el, index) {
    if (index - acc.cur > 1) {
      for (var i = acc.cur + 1; i < index; i++) {
        acc.res.push(i);
      }
    }
    acc.cur = index;
    return acc;
  }, {
    cur: -1,
    res: []
  });
  var missed = result.res;
  if (result.cur !== arr.length) {
    for (var i = result.cur + 1; i < arr.length; i++) {
      missed.push(i);
    }
  }
  return missed;
}

var a = [1, 2, 3, , 4, 5];
var missed = findMissed(a);
printRes(a, missed);

console.log(missed)

a = [1, , 3, , 5, , 7, , 9]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);

a = [1, ,,,]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);

a = [,,,]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);

a = [,,,2]
var missed = findMissed(a);
console.log(missed)
printRes(a, missed);



function printRes(src, res) {
  document.getElementById('res').innerHTML += JSON.stringify(src) + '<br/>' + JSON.stringify(res) + '<br/>';
}
<div id="res"></div>

#7


0  

Assuming there are two characters that you know aren't in the data (such as a pound sign # and pipe |), you can use this one-liner:

假设您知道有两个字符不在数据中(例如井号#和管道|),您可以使用这个单行:

Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1);

The 9s are simply placeholders in case the missing element is at the beginning or end. (But note that a single extra comma at the end of an array is ignored in JavaScript, so there's no way to check for that condition.)

9s只是占位符,以防缺少的元素在开头或结尾。 (但请注意,在JavaScript中会忽略数组末尾的一个额外逗号,因此无法检查该条件。)

Snippet

片段

console.clear();

//hole at beginning:
a= [,1,2,3,4,5];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //0

//hole in middle:
a= [1,2,3,,4,5];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //3

//an extra comma at the end of an array is ignored in JavaScript:
a= [1,2,3,4,5,];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //-1  

//only the last comma is ignored:
a= [1,2,3,4,5,,];
console.log(Math.max(-1, [].concat(9, a, 9).join('#|#').split('|').indexOf('##')-1));  //5

#8


-1  

Creating an array like so a=[1,2,3,,4,5]; will cause a[3] to be undefined and not null.

像这样创建一个数组a = [1,2,3 ,, 4,5];将导致[3]未定义而不为空。

a.indexOf(undefined) or a.indexOf('undefined') will not work for obvious reason. Setting a[3] to null will not work either since everything that follows will be shifted left.

a.indexOf(未定义)或a.indexOf('undefined')将无法正常工作。将[3]设置为null将不起作用,因为后面的所有内容都将向左移位。

I recommend creating your own array method that will search for every undefined value.

我建议您创建自己的数组方法,以搜索每个未定义的值。

var arr = [1,2,3,,4,5];

Array.prototype.findMissingValues = function(callback){
    for(var i = 0; i < this.length; i++){
        if(typeof this[i] === 'undefined'){

            if(typeof callback != 'undefined'){
                callback.apply(this, [i, this[i]]);
            }
        }
    }
}
arr.findMissingValues(function(index, value){
    alert(value);
});