TypeScript/JavaScript 中的 array.indexOf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35207093/
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
array.indexOf in TypeScript/JavaScript
提问by Hongbo Miao
UPDATE: Although this question is marked as duplicated with this. But @ssube's way is neat and much smarter.
更新:虽然这个问题被标记为与此重复。但是@ssube 的方式很整洁,也更聪明。
UPDATE2: Seems there is new way to do it in the comment by @Grungondola.
UPDATE2:@Grungondola 的评论中似乎有新的方法可以做到这一点。
I am using Typescript.
我正在使用打字稿。
This works well.
这很好用。
var array1 = [];
array1.push(5);
array1.push(6);
console.log("a", array2.indexOf(6));
But this does not work well. Because array2.indexOf returns -1 which means it does not find it.
但这效果不佳。因为 array2.indexOf 返回 -1 这意味着它没有找到它。
var array2 = [];
array2.push({aa:5,bb:5});
array2.push({aa:6,bb:6});
console.log(array2.indexOf({aa:6,bb:6}));
Looks like indexOf does not support Object. Does TypeScript have its own ways to deal with this kind of problem? Thanks.
看起来 indexOf 不支持 Object。TypeScript 有自己的方法来处理这类问题吗?谢谢。
回答by ssube
No. The problem is not with Object
, but that you are creating two different objects.
不。问题不Object
在于 ,而在于您正在创建两个不同的对象。
The object literal syntax ({foo: 'bar'}
) declares an object inline. When the script is executed, the object is created. Using that syntax multiple times creates multiple objects.
对象字面量语法 ( {foo: 'bar'}
) 声明一个内联对象。执行脚本时,将创建对象。多次使用该语法会创建多个对象。
You can easily test that with {foo: 3} === {foo: 3}
. This will evaluate to false, but they are not the same object (reference).
您可以使用{foo: 3} === {foo: 3}
. 这将评估为假,但它们不是同一个对象(引用)。
The indexOf
method checks if the object, string, number, etc, is present in the array. You're passing a new object, which is not in the array.
该indexOf
方法检查对象、字符串、数字等是否存在于数组中。您正在传递一个不在数组中的新对象。
If you have a reference to the object, you can use that and indexOf
will work:
如果您有对该对象的引用,则可以使用它并且indexOf
可以正常工作:
var foo = {aa:5,bb:5}, bar = {aa:6,bb:6};
var array2 = [];
array2.push(foo);
array2.push(bar);
console.log(array2.indexOf(foo));
Because you're referring to the same instance, this will print the index.
因为您指的是同一个实例,所以这将打印索引。
You can also use filter
or find
with a predicate to perform a deep search:
function deepIndexOf(arr, obj) {
return arr.findIndex(function (cur) {
return Object.keys(obj).every(function (key) {
return obj[key] === cur[key];
});
});
}
var array2 = [];
array2.push(foo);
array2.push(bar);
console.log(deepIndexOf(array2, foo));
This won't recurse into nested objects, but will accomplish the comparison you're looking for (equivalence on two objects and their immediate fields).
这不会递归到嵌套对象中,但会完成您正在寻找的比较(两个对象及其直接字段的等效性)。