1, perform calculations to all 'age', such as age = age+1
What you're doing there is looping through an array. There are lots of ways to do that in JavaScript; see this answer for a long list. In modern JavaScript, forEach
is common:
x.forEach(function(entry) {
entry.age = entry.age + 1;
// more commonly written like this:
// ++entry.age;
});
Note how each array entry is given to our callback function as the first argument.
Or alternately, the venerable old for
loop:
var index;
for (index = 0; index < x.length; ++index) {
x[index].age = x[index].age + 1;
// more commonly:
// ++x[index].age;
}
Note how we have to look up the entry by index, x[index]
.
2, put calculated data into object collection // x.push(age) I guess?
Well, if we update age
on the objects, it's already there. Alternately, we could create a new array with the results using map
:
var newArray = x.map(function(entry) {
return entry.age + 1;
});
Now, newArray
is an array of numbers, the result of adding 1 to each age.
But based on your question #3, more likely you want to add a new property with the updated age:
x.forEach(function(entry) {
entry.updatedAge = entry.age + 1;
});
3, print out 'x' in this way:
That's another loop:
x.forEach(function(entry) {
console.log(entry.name + " is " + entry.age + " " + entry.ending + " " + entry.updatedAge);
});
Live Example:
var x = [{name:"Ann",age:1,ending:'years old'},
{name:"Bob",age:2,ending:'years old'},
{name:"Cat",age:3,ending:'years old'},
{name:"Dog",age:10,ending:'years old'},
{name:"Fly",age:5,ending:'years old'}];
x.forEach(function(entry) {
entry.updatedAge = entry.age + 1;
});
x.forEach(function(entry) {
snippet.log(entry.name + " is " + entry.age + " " + entry.ending + " " + entry.updatedAge);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can, of course, do it all in one loop:
x.forEach(function(entry) {
snippet.log(entry.name + " is " + entry.age + " " + entry.ending + " " + (entry.age + 1));
// Note the () ----------------------------------------------------------^-------------^
});
Live Example:
var x = [{name:"Ann",age:1,ending:'years old'},
{name:"Bob",age:2,ending:'years old'},
{name:"Cat",age:3,ending:'years old'},
{name:"Dog",age:10,ending:'years old'},
{name:"Fly",age:5,ending:'years old'}];
x.forEach(function(entry) {
snippet.log(entry.name + " is " + entry.age + " " + entry.ending + " " + (entry.age + 1));
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>