如何在 JavaScript 中的 array.map 访问先前迭代的元素?
我们说有以下数组 -
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'Javascript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ];
现在,使用 map() 的概念。代码如下 -
示例
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'JavaScript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ]; var output = details.map((detailsObject, index) => { var tempObject = {}; tempObject.subjectId= detailsObject.subjectId; tempObject.subjectName = detailsObject.subjectName; const getThePreviousObject = index != 0 ? details[index-1] : null; tempObject.previousSubjectName = getThePreviousObject ? getThePreviousObject.subjectName : 'Not Available' return tempObject; }) console.log(output);
要运行以上程序,你需要使用以下命令 -
node fileName.js.
此处的文件名是 demo204.js。
输出
这将产生以下输出 -
PS C:\Users\Amit\javascript-code> node demo204.js [ { subjectId: 110, subjectName: 'Java', previousSubjectName: 'Not Available' }, { subjectId: 111, subjectName: 'JavaScript', previousSubjectName: 'Java' }, { subjectId: 112, subjectName: 'MySQL', previousSubjectName: 'JavaScript' }, { subjectId: 113, subjectName: 'MongoDB', previousSubjectName: 'MySQL' } ]
广告