Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแก้ไข map() ที่ไม่บันทึกองค์ประกอบใหม่ใน JavaScript

คำอธิบาย

ใช้ map() ให้ถูกต้องเพื่อสร้างอาร์เรย์ใหม่จากอาร์เรย์เดิม โดยเพิ่มค่าดัชนีเข้าไปในแต่ละองค์ประกอบ

ตัวอย่างโค้ด

const addIndexValueToArrayElement = function (arrObject) {
  const updatedArrayValue = [];
  arrObject.forEach(function (ob) {
    const mapValue = ob.map(function (value) {
      return value + arrObject.indexOf(ob);
    });
    updatedArrayValue.push(mapValue);
  });
  return updatedArrayValue;
};

const output = addIndexValueToArrayElement([
  [4, 5],
  [7, 56],
  [34, 78],
]);
console.log(output);

วิธีรัน

node fileName.js

ผลลัพธ์

[ [ 4, 5 ], [ 8, 57 ], [ 36, 80 ] ]