TypeScript / JavaScript中的array.indexOf [英] array.indexOf in TypeScript/JavaScript

查看:69
本文介绍了TypeScript / JavaScript中的array.indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:虽然此问题已标记为与此。但@ ssube的方式很整洁,更聪明。

UPDATE: Although this question is marked as duplicated with this. But @ssube's way is neat and much smarter.

UPDATE2:@Grungondola的评论似乎有新方法。

我正在使用Typescript。

I am using Typescript.

这很有效。

var array1 = [];
array1.push(5);
array1.push(6);
console.log("a", array2.indexOf(6));

但是效果不好。因为array2.indexOf返回-1,这意味着它找不到它。

But this does not work well. Because array2.indexOf returns -1 which means it does not find it.

var array2 = [];
array2.push({aa:5,bb:5});
array2.push({aa:6,bb:6});
console.log(array2.indexOf({aa:6,bb:6}));

看起来indexOf不支持Object。 TypeScript有自己的方法来处理这类问题吗?谢谢。

Looks like indexOf does not support Object. Does TypeScript have its own ways to deal with this kind of problem? Thanks.

推荐答案

没有。问题不在于 Object ,而在于您要创建两个不同的对象。

No. The problem is not with Object, but that you are creating two different objects.

对象文字语法( {foo:'bar'} )声明一个内联对象。执行脚本时,将创建对象。多次使用该语法创建多个对象

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:3} ==轻松测试= {foo:3} 。这将评估为false,但它们不是同一个对象(引用)。

You can easily test that with {foo: 3} === {foo: 3}. This will evaluate to false, but they are not the same object (reference).

indexOf 方法检查是否对象,字符串,数字等存在于数组中。你传递的是一个新对象,它不在数组中。

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:

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.

您还可以使用 过滤器 find ,带谓词进行深度搜索:

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

这篇关于TypeScript / JavaScript中的array.indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆