使用filter function findAllOccurrences(arr, target) { var newArr=[] arr.filter((item,index)=>{ if(item===target) newArr.push(index) }) return newArr }
使用reduce function findAllOccurrences(arr, target) { return arr.reduce((p,c,index)=>{c==target&&p.push(index);return p},[]) }
// 1. function findAllOccurrences(arr, target) { return arr.map((item, index) => item === target ? index : -1).filter(item => item !== -1) } // 2.function findAllOccurrences(arr, target) {constbuffer = []arr.forEach((item, index) => item === target && buffer.push(index))returnbuffer}
function findAllOccurrences(arr, target) { var a = []; arr.forEach(function(item, index) { return item === target && a.push(index); }); return a; } function findAllOccurrences(arr, target) { return arr.map(function(item, index) { return item === target ? index : -1; }).filter(function(index) { return index > -1; }); }