javascript - Define native method to sort array based on property in array -
been working simple task bit , can't seem figure out issue is. have array of objects, each object has setindex property , want insert objects , maintain array ordered objects set indices. thought simple not seem working had expected.
the native method inserts, chunk checks if array empty seems evaluate true, , overwrites index 0 every time , not execute splice. think simple js missing, can't seem figure out.
array.prototype.insertatindex = function(item) { (i = 0; < this.length; i++) { if(i+1 > this.length) { if(this[i].setindex <= item.setindex && this[i+1].setindex >= item.setindex) { this.splice(i,0,item); } } } if(this[0].length == 0); { this[0] = item; } };
i run next test function
item1 = {setindex: 0,name: 'item1'}; item2 = {setindex: 1,name: 'item2'}; item3 = {setindex: 2, name: 'item3'}; item4 = {setindex: 3, name: 'item4'}; item5 = {setindex: 4, name: 'item5'}; console.log(item1.setindex); my_array = []; my_array.insertatindex(item2); console.log(my_array); my_array.insertatindex(item1); console.log(my_array); my_array.insertatindex(item5);
i have tried using if(this[0] == undefined) check if array empty nil works planned
you have:
for (i = 0; < this.length; i++) { if(i+1 > this.length) { // dead code
the maximum of i
(inside loop) this.length-1
. therefore, (i+1 > this.length)
can never true.
javascript web
No comments:
Post a Comment