Javascript:当元素存在于数组中时,为什么 indexOf 函数 returns -1?

Javascript: why indexOf function returns -1 when the element exist in the array?

我创建了一个矩阵,如下所示:

u = Array.from({ length: 100}, (v, i) => []);
console.log(u)

然后,在 运行 代码和填充矩阵之后。我特别想获取最小元素的索引 row.so 结果应该是 0 或 1。

act[i] = u.indexOf(Math.min.apply(null,u[i]));

但是,有时我会得到-1。我读到负数表示该元素不存在于数组中。 就我而言,它始终存在。

为了检查它是否存在,我使用了 console.log(),它确实一直存在,但出于某种原因,它仍然 return -1 作为索引。

你可以这样做:

循环您的矩阵,通过将行传入 Math.min() 函数来找到该行的最小值 - 使用 spread syntax const min_val = Math.min(...u[row]);(到 "unpack"数组项放入函数参数中)。使用 act[row] = min_val; 将这个最小值放入你的 act 数组中,或者使用 act[row] = u[row].indexOf(min_val); 将这个最小值的索引放入你的数组中(或者你可以两者都做)。

如果您不需要全部 min values/indexes(并且只需要按需给定的行),您可以只使用底部的函数。

const ROWS = 100;
const COLS = 5;

const u = Array.from({ length: ROWS}, (v, i) => []);

//let's fill the Matrix:
for (let row = 0; row < u.length; row++){
  for (let col = 0; col < COLS; col++){
    u[row].push(Math.random());
  }  
}

console.log(u)

//Create an array of all min values/indexes:
const act = Array(u.length);

for (let row = 0; row < u.length; row++){
  const min_val = Math.min(...u[row]);
  //put min value in:
  //act[row] = min_val;
  
  //or put min value index in:
  act[row] = u[row].indexOf(min_val);
  
  //or you could do both:
  //act[row] = [ min_val, u[row].indexOf(min_val) ];
}

console.log(act)

//if you just want to get any min index of any row on the fly use this function:
function getMinIndexAtRow(inputArr, row){
  const min_val = Math.min(...inputArr[row]);
  return u[row].indexOf(min_val);
}

//use it like this:
console.log(getMinIndexAtRow(u, 0));