我制作了addNotes函数,它工作得很完美。 然后,我也做了移除函数,它工作得很好,但在一段时间后,我得到了这个错误的添加和移除函数。
app.js-https://pastebin.com/ymeq2zax
yargs.command({
command : 'add',
describe : ':adds a new note',
builder: {
title: {
describe: 'note it down',
demandOption: true,
type: 'string'
},
body: {
describe: 'describe the note',
type:'string'
}
},
handler : function(argv) {
notes.addNotes(argv.title,argv.body)
}
})
notes.js-https://pastebin.com/vqjtwznc
const addNotes=function(title,body)
{
const notes=loadNotes()
var k=0
for(var i=0;i<notes.length;i++)
{
if(title===notes[i].title) k=1
}
if(k===0)
{
notes.push({
title: title,
body: body
})
saveNotes(notes)
console.log(chalk.green.bold("New Note Added!"))
}
else{
console.log(chalk.red.bold("Title already there"))
}
}
您使用deleteNotes[i]
,这使得Notes[i]
返回未定义的,但x的长度没有改变,因此当您使用for循环对其进行迭代时,您将在已删除索引处对undefined
进行迭代。 在底部固定。
delete
从对象中删除属性。 对于数组,这意味着整数索引(属性)处的对象将从数组对象中移除,但基础数组的长度不会更改。
如果使用for-in
或in
或hasownproperty(index)
,则会将该数组索引(属性)视为不存在,但基础数组在索引被删除的地方存在间隙,因此访问已删除的索引将返回未定义。
需要注意的是,这与将undefined
作为已删除索引中的值不同。 它实际上是一个空引用,其行为类似于访问对象上不存在的属性。
例如,delete x[3]
和x[3]=undefined
是不同的,其中主要的实际区别是,如果使用类似for-of
或foreach
的内容来迭代数组,则如果使用delete x[3]
,则数组将跳过索引3,而如果使用x[3]=undefined
,则它仍将迭代值为undefined的索引3。
请参见删除数组元素
删除数组元素时,数组长度不受影响。 即使删除数组的最后一个元素,这也是成立的。
当delete运算符移除数组元素时,该元素不再在数组中。 在下面的示例中,使用DELETE删除树[3]。
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
if (3 in trees) {
// this is not executed
}
如果希望数组元素存在但具有未定义的值,请使用未定义的值而不是delete运算符。 在下面的示例中,为trees[3]分配了未定义的值,但数组元素仍然存在:
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees[3] = undefined;
if (3 in trees) {
// this is executed
}
相反,如果您希望通过更改数组的内容来移除数组元素,请使用splice()方法。 在下面的示例中,使用splice()从数组中完全移除树[3]:
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
null
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
console.log(trees, trees.length, 3 in trees);
delete trees[3];
console.log(trees, trees.length, 3 in trees); // empty reference 3, 3 in trees is false
trees[3] = undefined;
console.log(trees, trees.length, 3 in trees); // 3 in trees is true
trees.splice(3,1);
console.log(trees, trees.length, 3 in trees)
// notice index 3 is gone and the length is now one less