Javascript 无法读取属性';标题';空值为0

Javascript 无法读取属性';标题';空值为0,javascript,node.js,Javascript,Node.js,我制作了addNotes函数,它工作得非常好。然后,我还制作了remove函数,它工作得很好,但过了一段时间,我发现add和remove函数都出现了这个错误 app.js- notes.js- const addNotes=函数(标题、正文) { const notes=loadNotes() var k=0 for(var i=0;i您使用delete notes[i],这使得notes[i]返回未定义,但x的长度没有改变,因此当您使用for循环对其进行迭代时,您将在已删除索引处对未定义的进行

我制作了addNotes函数,它工作得非常好。然后,我还制作了remove函数,它工作得很好,但过了一段时间,我发现add和remove函数都出现了这个错误

app.js-

notes.js-

const addNotes=函数(标题、正文)
{
const notes=loadNotes()
var k=0

for(var i=0;i您使用
delete notes[i]
,这使得
notes[i]
返回未定义,但x的长度没有改变,因此当您使用for循环对其进行迭代时,您将在已删除索引处对
未定义的
进行迭代

delete
从对象中删除属性。这对于数组意味着整数索引(属性)处的对象从数组对象中删除,但基础数组的长度不变。
如果在
或或中使用
for
hasOwnProperty(index)
它会将该数组索引(property)视为不存在,但基础数组在索引被删除的位置有一个间隙,因此访问已删除的索引会返回未定义

需要注意的是,这与将
未定义
作为已删除索引的值不同。它实际上是一个空引用,其行为类似于访问对象上不存在的属性。
例如,
delete x[3]
x[3]=undefined
是不同的,其中主要的实际区别是,如果使用
For of
forEach
对数组进行迭代,那么如果使用
delete x[3]
,它将跳过索引3,而如果使用
x[3]=未定义
它仍将使用未定义的值在索引3上迭代

删除数组元素时,数组长度不受影响。即使删除了数组的最后一个元素,这一点仍然有效

当delete运算符删除数组元素时,该元素不再位于数组中。在下面的示例中,树[3]将随delete一起删除

如果希望数组元素存在但具有未定义的值,请使用未定义的值而不是delete运算符。在以下示例中,为树[3]分配了未定义的值,但数组元素仍然存在:

如果要通过更改数组的内容来删除数组元素,请使用splice()方法。在以下示例中,使用splice()将树[3]从数组中完全删除:

var trees=[‘红杉’、‘海湾’、‘雪松’、‘橡树’、‘枫树’];
控制台。原木(树木,树木。长度,3英寸树木);
删除树[3];
console.log(trees,trees.length,trees中的3);//空引用3,trees中的3为false
树[3]=未定义;
console.log(trees,trees.length,树中为3);//树中为真
树木.拼接(3,1);
控制台.日志(树,树.长度,3英寸树)

//请注意,索引3已消失,长度现在减少了一个
delete只会将索引设置为空(删除引用),并且不会调整数组大小以删除元素。您需要在for循环中添加对空索引的处理,或者使用
notes.splice(i,1)
而不是
删除注释[i]
将其完全删除
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)
}
})
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"))
} 
}
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
if (3 in trees) {
    // this is not executed
}
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees[3] = undefined;
if (3 in trees) {
    // this is executed
}
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]