如何使用for循环填充数组?

时间:2017-12-03 18:21:42

标签: javascript arrays for-loop

我在学习如何使用for循环填充新变量方面遇到了很多麻烦。例如,如果我有var year = [2010, 2000, 1992];var age = [];

如何使用for循环填充年龄变量?

如果这是一个不好的例子,请不要使用它。我只想帮助理解如何填充空数组。



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);
  }
}
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

最好创建包含相关数据的对象。将nameage组合到person对象中会有所帮助。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

但您也可以像这样使用forEach

&#13;
&#13;
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);
&#13;
&#13;
&#13;

通过制作包含所有相关数据的对象,您的循环永远不会失去同步。如果您从persons阵列中删除某个人,那么他们的nameage将会合在一起。

更新:使用过滤器

&#13;
&#13;
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);
&#13;
&#13;
&#13;

或使用ES6箭头功能

&#13;
&#13;
    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);
&#13;
&#13;
&#13;

这会提供符合您Age under 24条件的人员数组。

答案 1 :(得分:2)

如果你只想用循环填充年龄数组,你可以试试这个:

let years = [2010, 2000, 1992],
  age = [],
  d = new Date().getFullYear();

years.forEach(year => age.push(d - year));
console.log(age);

关于年龄与名字之间的关系,我认为Intervalia解释了这一点。

答案 2 :(得分:0)

工作版。 请将其与您的代码进行比较,以查看差异。尽管重复使用括号符号,Arrays总是在我开始的时候得到了我的语法和不同语言的语法.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]);
    }
}