Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  183] [ 4]  / answers: 1 / hits: 5623  / 10 Years ago, thu, may 8, 2014, 12:00:00

So if I had:



A=['a','b','c'];
B=[];

for (var i = 0;i<7;i++){
B.push(A[i])
}


I would get



B=[a, b, c, undefined, undefined, undefined, undefined]


Instead I want



B= [a,b,c]


So I guess I would need something like



for (var i = 0;i<7;i++){
B.push(A[i] unless A[i] is undefined. Then don't push anything)
}


How would I do this in Javascript?


More From » arrays

 Answers
10

An Object Oriented Aspect



=> After that code, clean your array :



B.clean(); 


Known that clean is an extension of array Class(OOP context)



Array.prototype.clean=function(){
var newArray = [];
for(var index = 0; index < this.length; index++) {
if(this[index]) {
newArray.push(this[index]);
}
}
return newArray;
};

[#45437] Wednesday, May 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denzelc

Total Points: 637
Total Questions: 89
Total Answers: 88

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;