【问题标题】:Javascript: why indexOf function returns -1 when the element exist in the array?Javascript:当元素存在于数组中时,为什么 indexOf 函数返回 -1?
【发布时间】:2020-09-28 07:23:27
【问题描述】:

我创建了一个矩阵,如:

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

然后,在运行代码并填充矩阵之后。我想获取特定行中最小元素的索引。所以结果应该是 0 或 1。

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

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

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

【问题讨论】:

  • 内部数组中没有值。即使是这样,您也必须搜索相同的对象引用。
  • 我想我明白你想做什么(见我的回答),但总的来说,你应该包含足够的代码,这样我们就不需要猜测了。 (例如,包含“填充矩阵”的代码)stackoverflow.com/help/minimal-reproducible-example
  • 谢谢大家。我认为这解决了问题 act[i] = u[i].indexOf(Math.min.apply(null,u[i]));

标签: javascript arrays min indexof negative-number


【解决方案1】:

你可以这样做:

遍历您的矩阵,通过将行传递给Math.min() 函数来找到该行的最小值 - 使用spread syntax const min_val = Math.min(...u[row]);(将数组项“解包”到函数参数中)。使用act[row] = min_val; 将此最小值放入您的act 数组中,或者使用act[row] = u[row].indexOf(min_val); 将此最小值的索引放入您的数组中(或者您可以两者都做)。

如果您不需要所有最小值/索引(并且只需要按需给定的行),您可以使用底部的函数。

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));

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 2015-02-11
    • 2012-01-25
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多