简体   繁体   中英

JavaScript: Cannot get .push() command to work as intended

I'm trying to create a function that loops through each item in an index and notes a certain item's index when encountered. In this function, when the item 'contraband' is encountered in the loop, the index is noted added, and the.push() command I've written is supposed to append each new index into an empty called 'contrabandIndexes'. However, the command or some other part of the code is not working as intended because when I run the function through the sample array, it returns with an empty array.

Where did I go wrong here?

function scan(freightItems) {
    let contrabandIndexes = [];
    freightItems.forEach(function(freightItem) {
        if (freightItem === 'contraband') {
            contrabandIndexes.push();
        }
    });
    return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: ' + indexes);

The forEach Array method passes the index along with the element in question. So you can use that index value to append to your contrabandIndexes Array.

function scan(freightItems) {
    const contrabandIndexes = [];
    freightItems.forEach(function(freightItem, idx) {
        if (freightItem === 'contraband') {
            contrabandIndexes.push(idx);
        }
    });
    return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: ' + indexes);

Also you don't need the let contrabandIndexes = []; outside of the function. At least not in this snippet.

After looking what others had to share, I think you should see this:

 function SecurityGuard(){ this.band = [...arguments]; this.contraband = []; this.holds = []; this.keep = []; this.scan = array=>{ const b = this.band, h = this.holds, c = this.contraband; array.forEach((v, i)=>{ if(b.indexOf(v) === -1){ h.push({[v]:i}); } else{ c.push({[v]:i}); } }); return this; } this.keepHolds = ()=>{ const h = this.holds; h.forEach(o=>{ for(let i in o){ this.keep.push(i); } }); h.splice(0); return this; } this.dumpContraband = ()=>{ this.contraband.splice(0); return this; } } const sg = new SecurityGuard('gun', 'knife', 'noose'); sg.scan(['noose', 'gun', 'dog', 'gun', 'cat', 'zippers', 'knife', 'phone']); console.log(sg.holds); console.log(sg.contraband); sg.keepHolds(); console.log(sg.keep);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM