。
对于这个问题,我们可以编写一个函数,接收一个数组和一个匹配项作为参数。函数会遍历数组,查找与匹配项相同的元素,并将它们存储在一个新的数组中,最后返回这个新的数组。
以下是一个示例函数的实现(使用JavaScript):
function findMatches(arr, item) {
const matches = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === item) {
matches.push(arr[i]);
}
}
return matches;
}
这个函数会遍历给定的数组,如果当前元素与匹配项相同,则将其添加到matches
数组中。最后,返回matches
数组作为结果。
下面是这个函数的一些示例用法:
const array = [1, 2, 3, 2, 4, 2, 5];
const item = 2;
const matches = findMatches(array, item);
console.log(matches); // [2, 2, 2]
这个函数的时间复杂度是O(n),其中n是数组的长度。
领取专属 10元无门槛券
手把手带您无忧上云