如何获得multidimentional数组的indexOf?

时间:2017-12-08 13:06:47

标签: javascript arrays

我有一些麻烦让indexOf成为一个多维数组。

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z[0].indexOf('ffffff');
alert(index); #returns -1

如您所见,十六进制值和数字(像素数量)位于z的同一列表中。

如何过滤并获取indexOf正确的列表?

2 个答案:

答案 0 :(得分:5)

  

如何过滤并获取indexOf正确的列表?

可以使用filter,但我不会;我会使用findIndex *:

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z.findIndex(function(entry) {
  return entry.indexOf("ffffff") != -1;
});
console.log(index);

findIndex返回您的回调返回真值的第一个条目的索引。

这只是告诉你外部索引(1)。如果你想要两个索引,我可能会使用some **并让回调接近结果变量:

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var outerIndex, innerIndex;
var index = z.some(function(entry, index) {
  var n = entry.indexOf("ffffff");
  if (n != -1) {
    outerIndex = index;
    innerIndex = n;
    return true;
  }
});
console.log(outerIndex, innerIndex);

在ES2015中添加了

* findIndex,但这对于polyfill来说是微不足道的;请参阅链接的MDN文章以获取polyfill。

** some早在2009年就已经来自ES5了,所以除了像IE8这样真正过时的浏览器之外,它还会出现在所有内容上。也是可以填充的。

答案 1 :(得分:0)

我编写了一个快速而又脏的深度indexOf函数,它返回一个索引数组:

Object.prototype.deepIndexOf = Array.prototype.deepIndexOf = function (v) {
    for (var i in this) {
        if (this[i] === v) {
            return [i];
        }

        if ('object' === typeof this[i]) {
            var t = this[i].deepIndexOf(v);
            if (t !== undefined) {
                t.unshift(i);
                return t;
            }
        }
    }
    return undefined;
}

在某些情况下,这可能会失败,但适用于简单的数组和对象:

Object.prototype.deepIndexOf = Array.prototype.deepIndexOf = function(v) {
	for(var i in this) {
  	if(this[i] === v) {
    	return [i];
    }

    if('object' === typeof this[i]) {
    	var t = this[i].deepIndexOf(v);
      if(t !== undefined) {
      	t.unshift(i);
      	return t;
      }
    }
  }
  return undefined;
}

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];

var z2 = {
	hello: {
  	world: 5
  },
  bye: {
  	world: 3,
    earth: 4
  }
}

console.log(z.deepIndexOf('ffffff'));
console.log(z2.deepIndexOf(4));

// And even very deep objects/arrays:

var verydeep = {
    one: {
        two: [
            [
                {
                    five: {
                        six: [
                            'Hello'
                        ]
                    }
                }
            ]
        ]
    }
}

console.log(verydeep.deepIndexOf('Hello'))

输出:

[
  "1",
  "0"
]
[
  "bye",
  "earth"
]
[
  "one",
  "two",
  "0",
  "0",
  "five",
  "six",
  "0"
]