簡體   English   中英

如何用for循環填充數組?

[英]How to fill an array with a for loop?

我在學習如何使用for循環填充新變量時遇到很多麻煩。 例如,如果我有var year = [2010, 2000, 1992]; var age = [];

如何使用for循環填充age變量?

如果這是一個不好的例子,請不要使用它。 我只想了解一些如何填充空數組的幫助。

 var names = ["Ace", "yoshi", "Lassie"]; var age = [25, 23, 5]; var u24 = []; for (var i = 0; i < names.length; i++) { if ([age] < 24) { u24 += age[i] console.log("hello " + names + " " + "you are" + age); } } 

最好創建包含相關數據的對象。 nameage到一個人對象中會有所幫助。

 var persons = [ { name: "Ace", age: 25 }, { name: "yoshi", age: 23 }, { name: "Lassie", age: 5 } ]; var u24=[]; for (var i =0; i < persons.length; i++) { var person = persons[i]; if(person.age < 24){ u24.push(person.age); console.log("hello " + person.name + " " + "you are " + person.age); } } console.log(u24); 

但是您也可以像這樣使用forEach

 var persons = [ { name: "Ace", age: 25 }, { name: "yoshi", age: 23 }, { name: "Lassie", age: 5 } ]; var u24=[]; persons.forEach( function(person) { if(person.age < 24){ u24.push(person.age); console.log("hello " + person.name + " " + "you are " + person.age); } } ); console.log(u24); 

通過使對象包含所有相關數據,您的循環將永遠不會失去同步。 如果您從persons數組中刪除人員,則其nameage將一起顯示。

更新:使用過濾器

 var persons = [ { name: "Ace", age: 25 }, { name: "yoshi", age: 23 }, { name: "Lassie", age: 5 } ]; var youngPersons = persons.filter( function(person) { return (person.age < 24); } ); console.log(youngPersons); 

或使用ES6箭頭功能

  var persons = [ { name: "Ace", age: 25 }, { name: "yoshi", age: 23 }, { name: "Lassie", age: 5 } ]; var youngPersons = persons.filter((person) => person.age < 24); console.log(youngPersons); 

這將Age under 24條件提供一系列與您的Age under 24相匹配的人。

如果您要做的只是用循環填充age數組,則可以嘗試以下操作:

 let years = [2010, 2000, 1992], age = [], d = new Date().getFullYear(); years.forEach(year => age.push(d - year)); console.log(age); 

關於年齡和名字之間的關系,我認為Intervalia對此做了解釋。

工作版本。 請將其與您的代碼進行比較以查看差異。 剛開始時,數組總是讓我着迷,盡管使用了方括號符號,但跨語言的語法卻有所不同。AutoIt語言仍然使我感到困惑:P

var names = ["Ace", "yoshi", "Lassie"];
var age = [25, 23, 5];
//Use array.push() to append values
var u24 = [];

//variable i counts up to names.length
//because i++ means 'add one' to i

for (var i = 0; i < names.length; i++) {
    //if ([age] < 24) {u24 += age[i];
    //age at the count 'i' (which is
    //counting)
    //is achieved by array[at_index]
    if (age[i] < 24) {
        u24.push(age[i]); //add it to the end
        console.log("Hello " + names[i] +
          ", you are " + age[i]);
    }
}

暫無
暫無

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

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