簡體   English   中英

如何用for循環制作多維數組?

[英]how to make multi dimensional array with for loop?

FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i=0 ;i<10;i++){
    contacts[i] = [];
    for(c=0;c<3;c++){
        contacts[i].push(FirstName);
        contacts[i].push(LastName);
        contacts[i].push(Adress);
    }
}

代碼為我提供了包含10個數組的contacts數組,每個數組具有重復3次的信息

您不需要第二個for循環:

FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
    contacts[i] = [];
    contacts[i].push(FirstName);
    contacts[i].push(LastName);
    contacts[i].push(Adress);
}

或者,您也可以使用這種方式:

FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
    contacts[i] = [FirstName, LastName, Adress];
}

我不確定目標,但我認為您應該使用對象而非二維數組來存儲信息。 顯示二維數組和帶有對象的數組的Jsfiddle )。 所以代替

var contacts = [
  ['John', 'Doe', '100 Main Street'],
  ['Jane','Smith','101 Main']
];

你將會擁有

var contacts = [
  {
    first_name: 'John',
    last_name: 'Doe', 
    address: '100 Main Street'
  },
  {
    first_name: 'Jane',
    last_name: 'Smith', 
    address: '101 Main Street'
  }
];

嘗試這個。 它將表單名稱和電子郵件推送到聯系人

<form onsubmit='formSubmit(event);'>
  <label>name</label>
  <input id='name' value='John'/>
  <label>email</label>
  <input id='email' value='fake@test.com'/>
  <br/>
  <button>
  add name and email
  </button>
</form>

function formSubmit(event){
    event.preventDefault();
    contacts.push({
      name: document.getElementById('name').value,
      email: document.getElementById('email').value
    })
    console.log(contacts);
}

暫無
暫無

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

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