Alexander Kundurdjiev Alexander Kundurdjiev - 4 months ago 9
Javascript Question

separate object inheritance on two looping group results

I have an array on which items I want to use object inheritance with two difference results. The problem is that changing value of object property in second condition affect object property value in first condition too.
What I want is first two items to have record 1 and rest items to have record 8. The way I want to achieve this is only through object inheritance.
https://plnkr.co/edit/Uu09kivq1eGpeM5WczaO?p=preview

javascript:

// Code goes here
var html = '';

var NamesRecord = function(){}
NamesRecord.prototype.number = 1

var myArray = [
{
name: 'item1',
record: null
},
{
name: 'item1',
record: null
},
{
name: 'item1',
record: null
},
{
name: 'item1',
record: null
},
{
name: 'item1',
record: null
}]


for(var i = 0; i< myArray.length; i++){

if(myArray.length < 3){
myArray[i].record = new NamesRecord()
}

if(myArray.length >= 3){
myArray[i].record = new NamesRecord()
myArray[i].record.number = 8
}

html += '<div> <strong>Name: </strong>' + myArray[i].name + '<strong>Record: </strong>' + myArray[i].record.number + '</div>'

}

document.body.innerHTML += html;


html results:

Name: item1 Record: 8
Name: item1 Record: 8
Name: item1 Record: 8
Name: item1 Record: 8
Name: item1 Record: 8


desired results:

Name: item1 Record: 1
Name: item1 Record: 1
Name: item1 Record: 8
Name: item1 Record: 8
Name: item1 Record: 8

Answer

In the two if statements inside the for loop, you should be checking i instead of myArray.length. The myArray.length is always the same 5, since you've built myArray it in advance and you're not adding nor removing anything from it.

Comments