The secret to wholesale...

In the article about buying Thai goods, I introduced wholesale markets and cheap...

Restaurant business and the...

Customers are a special figure in restaurants. This may seem obvious, but...

Guide the clues to...

Japanese goods Known for putting quality first. However, in the past, due...

Online cosmetics business and...

Starting a business, especially online cosmetics business is the silver trend and...
HomeLập trìnhJavaScriptTrả về Javascript...

Trả về Javascript không hoạt động – JavaScript


//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["JavaScript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(name, prop){
// Only change code below this line
  contacts.forEach(contact => {
      if (contact.hasOwnProperty("firstName")) {
          if (contact["firstName"] == name) {
              if (contact.hasOwnProperty(prop)) {
                  console.log(`found ${contact[prop]}`);
                  return contact[prop];
              } else {
                  return "No such property"
              }
          }
      } else {
          return "No such contact"
      }
  })
  

  
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");


Bạn có thể giải thích ý của bạn khi trả về không hoạt động không? Bạn đang mong đợi điều gì mà nó không làm?

Câu lệnh trả về của bạn đang trả về từ cuộc gọi lại forEach, bạn không có bất kỳ điều gì trả về từ cuộc gọi lại lookUpProfile chức năng, nếu đây là điều

sử dụng return bên trong vòng lặp forEach sẽ không phá vỡ vòng lặp. Sau khi chạy mã của bạn với lookUpProfile("Akira", "likes"); Tôi có thể thấy console.log() có liên quan, nhưng vì bạn không thể return ra khỏi vòng lặp forEach, hàm của bạn sẽ trả về không xác định.



Zik.vn – Biên dịch & Biên soạn Lại

Đọc thêm  Phương thức reduce và reduceRight của JavaScript hoạt động như thế nào
spot_img

Create a website from scratch

Just drag and drop elements in a page to get started with Newspaper Theme.

Buy Now ⟶

Bài viết liên quang

DMCA.com Protection Status