You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求解析util工具文件中inOf与oneOf方法的实现逻辑

Hey there, let's unpack these two utility methods clearly for you:

1. util.inOf(arr, targetArr)

First, here's the original code:

util.inOf = function (arr, targetArr) {
  let res = true;
  arr.map(item => {
    if (targetArr.indexOf(item) < 0) {
      res = false;
    }
  });
  return res;
};

What it does

This method checks if every element in the first array (arr) exists in the second target array (targetArr). It returns true only if all items from arr are present in targetArr; otherwise, it returns false.

How it works

  • We start by setting a result flag res to true, assuming all items are present initially.
  • We loop through each item in arr using map (a quick note: map is designed for transforming arrays, not just looping—using forEach here would be more semantically accurate).
  • For each item, we check if it exists in targetArr with indexOf(item). If indexOf returns -1, that means the item isn't in targetArr, so we flip res to false.
  • Finally, we return the res flag.

A cleaner, more efficient alternative

You can simplify this with the native every method, which stops looping as soon as it finds a mismatch (saves unnecessary iterations compared to the original code):

util.inOf = function (arr, targetArr) {
  return arr.every(item => targetArr.includes(item));
};

2. util.oneOf(ele, targetArr)

Here's the original code:

util.oneOf = function (ele, targetArr) {
  if (targetArr.indexOf(ele) >= 0) {
    return true;
  } else {
    return false;
  }
};

What it does

This method checks if a single element (ele) exists in the target array (targetArr). It returns true if the element is found, false otherwise.

How it works

  • We use targetArr.indexOf(ele) to get the element's position in the array. If the element exists, indexOf returns its index (which is >= 0); if not, it returns -1.
  • The if/else block just converts that index check into a straightforward boolean return value.

A cleaner alternative

You can shorten this to a one-liner using includes, which makes the intent more explicit:

util.oneOf = function (ele, targetArr) {
  return targetArr.includes(ele);
};

内容的提问来源于stack exchange,提问作者sof-03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:14:01