Reputation: 3
Question: Develop an array of 1000 objects (having properties name and number as shown).
got
(which is a variable inside the object) which will contain every little
object that evenly divided the higher.My code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var n = 1000;
var sample = [];
for (var i = 0; i < n; i++) sample.push({
name:'John' + i,
value: i
});
console.log(sample);
function Converter() {
var n = 1000;
var higher = sample;
for (var i = 0; i < n; i++) higher.name = 'John' + i;
higher.value = i * 5;
console.log(higher);
}
</script>
</body>
</html>
The array of objects is created and it is as expected/required by the question, however, the converter
function for higher
does not work, also how should the 3rd question be done?
Upvotes: 0
Views: 78
Reputation: 12990
You should also try to think in a more structured manner about your code here. I would suggest writing separate functions for each problem and giving them meaningful names. Perhaps something like the following:
var n = 1000;
var sample = [];
for (var i = 0; i < n; i++) sample.push({
name: 'John' + i,
value: i
});
console.log(sample);
var higher = convertToHigher(sample);
var little = convertToLittle(sample);
var higherWithDivisors = findAllDivisors(higher, little);
function convertToHigher(arr) {
var newArr = [];
// TODO: iterate through each entry in arr, create a new modified object
// with a higher value and add it to newArr
return newArr;
}
function convertToLittle(arr) {
var newArr = [];
// TODO: iterate through each entry in arr, create a new modified object
// with a lower value and add it to newArr
return newArr;
}
function findAllDivisors(arr1, arr2) {
var newArr = [];
// TODO: solve problem 3 here
return newArr;
}
Upvotes: 1
Reputation: 138235
Some thoughts:
1) only constructors should start with a capital letter, functions should be camelcase by convention so it should be converter
2) you don't call converter()
so it never gets executed
3) make sure to indent your code properly var n
and var sample
should be at the same depth.
4) if you omit the brackets after an if
or for
, only the following statement gets inside the branch, so in your case you do:
for (var i = 0; i < n; i++)
higher.name = 'John'+i;
higher.value = i*5;
so the second line isn't even executed in the loop, you want:
for (var i = 0; i < n; i++) {
higher.name = 'John'+i;
higher.value = i*5;
}
5) higher.name
makes little sense as higher
is an array, you want to change the name of the i
th higher
number which you can do with higher[i].name
6) "John1"
is not in caps, you want to call toUpperCase
on it (("John1").toUpperCase()
)
also how should the 3rd question be done?
I guess fixing your code and doing the second question is enough for today.
You could continue reading:
Upvotes: 2