题目描述
在数组 arr 中,查找值与 item 相等的元素出现的所有位置
示例1
输入
['a','b','c','d','e','f','a','b','c'] 'a'
输出
[0, 6]
-
way1:逻辑路运算符:||的短路用法;
/** * 运行时间:1357ms * * 占用内存:77772k */ function findAllOccurrences(arr, target) { let result=[]; arr.forEach(function(currentValue,currentIndex,sourceArray){ currentValue!==target||result.push(currentIndex); }); return result; } -
way2: for循环:
/** * 运行时间:1332ms * * 占用内存:77844k * */ function findAllOccurrences(arr, target) { var a = []; for(var i = 0; i < arr.length; i++){ if(target == arr[i]) a.push(i); } return a; }