ts 检测数组中是否包括某个元素的二个方法

1、includes

 let cells = graph.getCells();
    let childrenX = [] as number[];
    let childrenY = [] as number[];
    let children = [] as any[];
    cells.forEach((cell) => {
      let data = cell.store.data.attrs.data; // 获取每个节点的data属性
      if (data.notetype == '物资类') {
        let childX = cell.getBBox().x;
        let childY = cell.getBBox().y;
        if (!childrenX.includes(childX)) {
          childrenX.push(childX);
          childrenY.push(childY);
        }
        children.push(cell);
      }
    });

以上代码是基于@antv/x6的一些方法,includes:

if (!childrenX.includes(childX)) {
          childrenX.push(childX);
          childrenY.push(childY);
        }

includes:返回true,false,根据这个判断就可以。

2、indexOf,这个与js的一致,只要判断是不是==-1即可。

小技巧,但经常会用到。

### TypeScript 中 `indexOf` 方法的使用 在 TypeScript 中,`indexOf` 是用于查找数组或字符串中特定元素位置的方法。对于数组而言,该方法返回给定元素第一次出现的位置;如果未找到则返回 `-1`。 #### 数组中的 `indexOf` 下面是一个简单的例子来展示如何在一个整数数组里寻找某个数值: ```typescript const numbers: number[] = [1, 2, 3, 4, 5]; console.log(numbers.indexOf(3)); // 输出:2 ``` 当尝试定位不存在于列表内的项目时,将会得到负一作为回应[^1]。 #### 字符串中的 `indexOf` 同样地,在字符串操作方面也可以应用这个功能。它会告知子串首次显现之处(基于零索引),找不到的话同样是给出 -1 结果。 ```typescript const text: string = "hello world"; console.log(text.indexOf('world')); // 输出:6 ``` ### 替代方案 尽管 `indexOf` 提供了一种基本的方式来进行匹配检测,但在某些情况下可能存在更好的选择。以下是几种常见的替代品: - **`includes()`**: 这个 API 可用来判断目标序列是否存在指定成员,而无需关心具体位次。其优点在于语义更加直观易懂,并且支持传入第二个参数表示起始搜索位置。 ```typescript const fruits: string[] = ['apple', 'banana']; console.log(fruits.includes('orange')); // 输出:false ``` - **`findIndex()` / `find()`**: 当需要获取满足条件的第一个元素及其下标时可以考虑这两个函数。前者仅提供索引值,后者则是直接返回对象本身。 ```typescript interface Item { id: number; name: string; } const items: Item[] = [ {id: 1, name: 'item one'}, {id: 2, name: 'special item'} ]; console.log(items.findIndex(item => item.name === 'special item')); // 输出:1 console.log(JSON.stringify(items.find(item => item.name === 'special item'))); // 输出:"{"id":2,"name":"special item"}" ``` - **正则表达式 (`RegExp`) 配合 `test()`, `matchAll()` 或者其他相关方法** : 对复杂模式识别特别有效率,比如验证邮箱地址格式等场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值