javascript 在复杂数组上使用 indexOf 时遇到问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8670345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:10:59  来源:igfitidea点击:

Trouble using indexOf on a complex array

javascriptarraysindexof

提问by Nick

Possible Duplicate:
indexOf method in an object array?

可能的重复:
对象数组中的 indexOf 方法?

I have a javascript array which follows this format:

我有一个遵循这种格式的 javascript 数组:

var arrayName = [
{id: "a", gender: "man",   item: "stuff"},
{id: "b", gender: "woman", item: "stuff"},
{id: "c", gender: "man",   item: "stuff"},
{id: "d", gender: "man",   item: "stuff"}
];

Is there a way that I can use array.indexOf to find an index in the array, when for example I know the "id" variable.

有没有一种方法可以使用 array.indexOf 来查找数组中的索引,例如,当我知道“id”变量时。

For example I tried;

例如我试过;

var position = arrayName.indexOf("b");
arrayName[position].gender = "man"

At the moment I am using;

目前我正在使用;

for(var i=0; i<arrayName.length; i++) {
   if(arrayName[i].id == "b"){
       arrayName[i].gender = "man";
   }
}

This second technique works but the actual array I am using has 150 entries and 10 items in each entry so looping through it all seems very wasteful when I know the "id" of the entry I want to edit. indexOf would be a much cleaner approach if I can get it working.

这第二种技术有效,但我使用的实际数组在每个条目中有 150 个条目和 10 个项目,因此当我知道要编辑的条目的“id”时,循环遍历它似乎非常浪费。如果我可以让它工作, indexOf 将是一种更清洁的方法。

回答by Adam Rackis

Your call to indexOfis checking the objects in your array against the string b, which will never work.

您的调用indexOf是根据字符串检查数组中的对象b,这将永远无法工作。

Looping through the array elements to find the right id is a simple solution.

循环遍历数组元素以找到正确的 id 是一个简单的解决方案。

Or, you could make your own indexOf function:

或者,您可以创建自己的 indexOf 函数:

Array.prototype.indexOfId = function(id) {
    for (var i = 0; i < this.length; i++)
        if (this[i].id === id)
            return i;
    return -1;
}

    var arrayName = [
      { id: "a", gender: "man", item: "stuff" },
      { id: "b", gender: "woman", item: "stuff" },
      { id: "c", gender: "man", item: "stuff" },
      { id: "d", gender: "man", item: "stuff" }];

    var position = arrayName.indexOfId("b");

    alert(position);  //alerts 1

Here's a fiddle

这是一把小提琴

EDIT

编辑

If you want to compare your array elements to any property, here's how you do it (note that I'm using [] syntax to get an arbitrary property)

如果要将数组元素与任何属性进行比较,请按照以下方法进行操作(请注意,我使用 [] 语法来获取任意属性)

    Array.prototype.indexOfField = function (propertyName, value) {
        for (var i = 0; i < this.length; i++)
            if (this[i][propertyName] === value)
                return i;
        return -1;
    }

    var position = arrayName.indexOfField("id", "b");
    alert(position);  //alerts 1

    position = arrayName.indexOfField("gender", "man");
    alert(position); //alerts 0


Or, if you don't want to mess with Array's prototype, and you don't mind using features not present in older browsers, you could use Array's filterfunction

或者,如果您不想弄乱 Array 的原型,并且不介意使用旧浏览器中不存在的filter功能,则可以使用 Array 的功能

var position = arrayName.indexOf(arrayName.filter(function (val) {
      return val.id === "b";
})[0]);

Note that this function is not present in IE8, and so to support this browser you'd have to grab the shim from MDN

请注意,此功能在 IE8 中不存在,因此要支持此浏览器,您必须从 MDN 中获取垫片

EDIT- oops, indexOf isn't friendly toward old browsers either. If you opt for this second bit of code and wanted to support IE, you'd also have to grab the shim for indexOf from here

编辑- 哎呀,indexOf 对旧浏览器也不友好。如果您选择第二部分代码并希望支持 IE,您还必须从这里获取 indexOf 的垫片

回答by NiKo

If you have the opportunity to, you can use Array.prototype.filter:

如果有机会,可以使用 Array.prototype.filter:

var arrayName = [
    {id: "a", gender: "man",   item: "stuff"},
    {id: "b", gender: "woman", item: "stuff"},
    {id: "c", gender: "man",   item: "stuff"},
    {id: "d", gender: "man",   item: "stuff"}
];

console.log(arrayName.filter(function(i) {
    return i.id === 'b';
}));

Which will give:

这将给出:

[ { id: 'b', gender: 'woman', item: 'stuff' } ]

回答by dku.rajkumar

you can override indexOfusing prototype

你可以覆盖indexOf使用prototype

Array.prototype.indexOf = function(elem) {
    for (var i = 0; i < this.length; i++){
        if (this[i].id === elem)
            return i;
    }
    return -1;
}

var arrayName = [
{id: "a", gender: "man",   item: "stuff"},
{id: "b", gender: "woman", item: "stuff"},
{id: "c", gender: "man",   item: "stuff"},
{id: "d", gender: "man",   item: "stuff"}
];

alert(arrayName.indexOf("b"));

fiddle : http://jsfiddle.net/r8rp9/1/

小提琴:http: //jsfiddle.net/r8rp9/1/