繁体   English   中英

JavaScript:无法 get.push() 命令按预期工作

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

我正在尝试创建一个 function 循环遍历索引中的每个项目,并在遇到某个项目的索引时记录下来。 在这个 function 中,当在循环中遇到“违禁品”项时,会注意到添加了索引,并且我编写的 .push() 命令应该将 append 每个新索引放入一个名为“contrabandIndexes”的空。 但是,该命令或代码的其他部分未按预期工作,因为当我通过示例数组运行 function 时,它返回一个空数组。

我在哪里 go 错了?

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);

forEach Array 方法将索引与相关元素一起传递。 因此,您可以将 append 的索引值用于您的contrabandIndexes数组。

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);

你也不需要let contrabandIndexes = []; 在 function 之外。 至少不在这个片段中。

在查看了其他人必须分享的内容后,我认为您应该看到以下内容:

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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