名为"notes"的数组包含5个对象,每个对象都有键
var notes = [
{
title: "Home",
message: "is a good story",
status: 'new',
author:"dala",
},
{
title: "School",
message: "Have to go everday",
status: 'new',
author:"aisha",
},
{
title: "study",
message: "we have exam to pass",
status: 'new',
author:"Omar",
},
{
title: "Work",
message: "dead line is close",
status: 'new',
author:"Said",
},
{
title: "homework",
message: "as today we need to do it",
status: 'new',
author:"Amal",
},
];
我想将所有笔记的状态更新为"已完成",错误是代码仅更新第一个对象
function map(notes,callback){
const newNotes =[];
for(var i=0; i<notes.length; i++) {
const result = callback(notes[i].status = "completed",i);
newNotes.push(result);
return newNotes;
}
}
var outp = map(notes,function(value, i){
console.log(i)
for(var a= 0; a<value.length; a++){
return notes;
}
})
console.log(outp);
我正在训练回调函数,这个训练代码是编写代码的问题 如果您有有用的资源可以学习,请与我分享
你不需要编写自己的map
函数,Array.prototype.map
已经做了你的map
函数所做的事情(还有更多,但这无关紧要)。
问题是:
- 您的
map
在for
循环中return newNotes;
,因此当循环仅完成其中一个元素时,它会返回。 map
未正确调用您的回调。- 您的回调没有执行
map
函数期望它执行的操作。
对回调的调用应该只是:
const result = callback(notes[i], i);
return newNotes;
应该在循环之后。
然后,你的回调应该创建一个新对象,其中包含传入的原始对象的属性,加上status: "completed"
——也许使用带有 spread 语法的对象文字,如下所示:
const output = map(notes, function(note, index) {
return {...note, status: "completed" };
});
在 map 函数中,您将newNotes
数组returned
在 for 循环中,而不是在它之后。但是,我建议使用内置的map
函数。
var notes = [
{
title: "Home",
message: "is a good story",
status: 'new',
author:"dala",
},
{
title: "School",
message: "Have to go everday",
status: 'new',
author:"aisha",
},
{
title: "study",
message: "we have exam to pass",
status: 'new',
author:"Omar",
},
{
title: "Work",
message: "dead line is close",
status: 'new',
author:"Said",
},
{
title: "homework",
message: "as today we need to do it",
status: 'new',
author:"Amal",
},
];
function map(notes,callback){
const newNotes =[];
for(var i=0; i<notes.length; i++) {
const result = callback(notes[i].status = "completed",i);
newNotes.push(result);
}
return newNotes;
}
var outp = map(notes,function(value, i){
console.log(i)
for(var a= 0; a<value.length; a++){
return notes;
}
})
console.log(outp);