簡體   English   中英

使用 forEach 遍歷數組

[英]Looping through array with forEach

我正在嘗試制作一個循環遍歷數組並將“位置”和“距離”記錄到控制台的基本程序。 我的程序沒有按預期運行,不會將值記錄到控制台。 我做錯了什么,我該如何解決?

let destinations = [
  {place: ['Dubai'],
  distance: 7276},
  {place: ['Sydney'],
  distance: 8759},
  {place: ['London'],
  distance: 4166},
  {place: ['tokyo'],
  distance: 5754},
  {place: ['Seoul'],
  distance: 6037},
];

destinations.forEach(spot => {
    if (spot.length < 6) {
      console.log(`${spot} is an interesting vacation spot.
      Let's see how far it is before we pull the trigger`);
      destinations.forEach(howFar => {
        if (howFar < 6000) {
          console.log(`${spot} is close enough. Let's go there!`);
        } if (howFar > 6000) {
          console.log(`Nevermind. ${spot} is too far.`);
        }});
    }
});

您需要非常仔細地逐步執行代碼,以嘗試查看 JS 解釋器看到的內容。 在草稿紙上記下變量的值以及它們在循環時如何變化會有所幫助。 這將幫助您看到自己的錯誤:

destinations.forEach(spot => {

什么是spot 它將是destinations的每個值,因此例如在第一次迭代中它將是{place: ['Dubai'],distance: 7276}

if (spot.length < 6) {

{place: ['Dubai'],distance: 7276}length屬性是多少? 這看起來不像它有length屬性。 它不是一個數組。 另外,你在這里檢查什么條件? 你確定你需要一個 if 語句嗎?

console.log(`${spot} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);

您希望看到什么在這里將spot放在字符串中? 它的值為{place: ['Dubai'],distance: 7276} 您確定不想從 object 中獲取一些值以放入字符串中嗎?

destinations.forEach(howFar => {

這不是在你之前循環過的同一個數組上循環嗎? 給定 6 個目的地,這意味着它將運行 36 次。 howFar是什么? 因為它來自destinations.forEach ,所以它將是destinations數組中的對象之一。

if (howFar < 6000) {

destinations數組中的 object 是否與數字相當? 它是一個 object,所以這是行不通的。 您是要訪問 object 的distance屬性嗎?

我的第一條建議是簡化您的destinations數組。 place目前是一個字符串數組,但它們都是單個項目,因此您可能不需要一個數組。 此外,由於您沒有更改destinations ,您可以將它設為一個const變量,這很有用,因為它可以讓查看您的代碼的人知道他們不必擔心找到可能發生變化的地方:

const destinations = [
  {place: 'Dubai', distance: 7276},
  {place: 'Sydney', distance: 8759},
  {place: 'London', distance: 4166},
  {place: 'Tokyo', distance: 5754},
  {place: 'Seoul', distance: 6037},
];

您循環遍歷目的地的方式很好,但是您需要訪問 object 的屬性,並且您不需要無關的內部循環和 if 語句(除非您打算用它做一些我不想做的事情理解)。

destinations.forEach(spot => {
  console.log(`${spot.place} is an interesting vacation spot.
    Let's see how far it is before we pull the trigger`);
  if (spot.distance < 6000) {
    console.log(`${spot.place} is close enough. Let's go there!`);
  } else {
    console.log(`Nevermind. ${spot.place} is too far.`);
  }
});

你基本上是在做一個 Object.length,它不存在。 試試 spot.place 或 spot.distance 之類的東西。

此外,您不能在目的地內執行 destinations.forEach。 這真的有必要嗎? 嘗試這樣的事情:

destinations.forEach(spot => {
if (spot.place.length < 6) {
  console.log(`${spot.place} is an interesting vacation spot.
  Let's see how far it is before we pull the trigger`);
  if (spot.distance < 6000) {
     console.log(`${spot.place} is close enough. Let's go there!`);
  } else {
      console.log(`Nevermind. ${spot.place} is too far.`);
  }
}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM