请求解析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
restotrue, assuming all items are present initially. - We loop through each item in
arrusingmap(a quick note:mapis designed for transforming arrays, not just looping—usingforEachhere would be more semantically accurate). - For each item, we check if it exists in
targetArrwithindexOf(item). IfindexOfreturns-1, that means the item isn't intargetArr, so we fliprestofalse. - Finally, we return the
resflag.
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,indexOfreturns its index (which is >= 0); if not, it returns-1. - The
if/elseblock 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

