在多维数组中进行比较以找到在其他多维数组中使用的正确索引失败

时间:2019-03-06 10:58:17

标签: javascript arrays multidimensional-array

我对Java语言中的函数有疑问:

我只是将一个输入数组与另一个数组进行比较,并根据结果返回一些东西,但是由于某种原因,我的比较无法正常工作...

这是我的功能:

const createArrayColor = (labels) => {
  const combi = [
    ["bronze","gold","new","silver"],
    ["bronze","gold","silver"],
    ["gold","new","silver"],
    ["bronze","gold","new"],
    ["bronze","new","silver"],
    ["gold","silver"],
    ["bronze","gold"],
    ["gold","new"],
    ["bronze","silver"],
    ["new","silver"],
    ["bronze","new"],
    ["gold"],
    ["silver"],
    ["bronze"],
    ["new"],
  ];

  const color = [
    ["#614E1A","#c49c48", "#f4f3f3", "#A5A49B"],
    ["#614E1A", "#c49c48", "#A5A49B"],
    ["#c49c48", "#f4f3f3", "#A5A49B"],
    ["#614E1A", "#c49c48", "#f4f3f3"],
    ["#614E1A", "#f4f3f3", "#A5A49B"],
    ["#c49c48", "#A5A49B"],
    ["#614E1A", "#c49c48"],
    ["#c49c48", "#f4f3f3"],
    ["#614E1A", "#A5A49B"],
    ["#f4f3f3", "#A5A49B"],
    ["#614E1A", "#f4f3f3"],
    ["#c49c48"],
    ["#A5A49B"],
    ["#614E1A"],
    ["#f4f3f3"],
  ];

  let i = 0;

  combi.forEach((c) => {
      console.log("Color: " + color[i]);
      console.log("Combi:  " + c + " ,type:  " + c.constructor.name );
      console.log("labels: " + labels + " ,type:  " + labels.constructor.name );
      console.log("Is it equal? " + (labels === c));

    if (labels === c) {
      return color[i];
    }
    i = i + 1;
  })
}

(顺便说一句,如果您知道如何在JS中进行数组的组合,我也想知道这一点,我敢肯定,有一种更好的方法可以做到我所做的但我没有找到)

因此,如您所见,我将labelscombi的每个元素进行比较,但它始终为false ...

Here are the results of the console.log

我认为这是我在某个地方犯的小错误,但我找不到它...

2 个答案:

答案 0 :(得分:1)

“ c”和“ labels”是两个具有确切内容的不同数组。请参见question,以了解如何比较数组。

答案 1 :(得分:0)

如果出于某种原因需要保留arrayInput8迭代器,则由于该数组是多维的2个深度,因此需要对该数组进行两次迭代。

这将找到给定值的第一次出现:

forEach