Javascript Node Js,我正在尝试停止添加重复项
我使用的是Node Js,我有一个列表生成器,可以添加和显示列表,但是我正在尝试更改它,以便不能添加重复的项,目前这不起作用Javascript Node Js,我正在尝试停止添加重复项,javascript,node.js,Javascript,Node.js,我使用的是Node Js,我有一个列表生成器,可以添加和显示列表,但是我正在尝试更改它,以便不能添加重复的项,目前这不起作用 const stdin = process.openStdin(); var items = []; stdin.on('data', function(chunk) { console.log(typeof chunk); var text = chunk.toString().trim(); console.log(typeof text);
const stdin = process.openStdin();
var items = [];
stdin.on('data', function(chunk) {
console.log(typeof chunk);
var text = chunk.toString().trim();
console.log(typeof text);
if (text.indexOf('add ') === 0) {
if(text.indexOf(items.value) === -1){
console.log("There is all ready something there");
}else{
var space = text.indexOf(' ');
var item = text.substring(space+1).trim();
console.log('adding "'+item+'"');
items.push(item);
}
}
if (text.indexOf('list') === 0) {
items.forEach(function(item, index) {
console.log(index+'. '+item);
});
}
})
您正在
文本中查找项。值(没有意义,但是…)而不是在项中查找文本:
if (text.indexOf('add ') === 0) {
var space = text.indexOf(' '); // NOTE: will always be 3, could just use that
var item = text.substring(space+1).trim()
if(items.indexOf(item) >= 0) {
console.log("There is already something there")
}
else {
items.push(item)
}
}