admin管理员组文章数量:1418618
I wanted make [1,2,3,4,5].duplicated()
works but when I wrote:
Array.prototype.duplicator = function (){
var a = [];
for(var i=0;i<10;i+=2){
a[i]=this[i];
a[i+1]=this[i];
}
return a;
};
[1,2,3,4,5].duplicator();
it returns [1, 1, 3, 3, 5, 5, undefined, undefined, undefined, undefined]
instead of [1,1,2,2,3,3,4,4,5,5]
. Can anyone tell me why it does not work?
I wanted make [1,2,3,4,5].duplicated()
works but when I wrote:
Array.prototype.duplicator = function (){
var a = [];
for(var i=0;i<10;i+=2){
a[i]=this[i];
a[i+1]=this[i];
}
return a;
};
[1,2,3,4,5].duplicator();
it returns [1, 1, 3, 3, 5, 5, undefined, undefined, undefined, undefined]
instead of [1,1,2,2,3,3,4,4,5,5]
. Can anyone tell me why it does not work?
9 Answers
Reset to default 5Array.prototype.duplicator=function()
{
return this.concat(this)
}
alert([1,2,3,4,5].duplicator());
You could just map
and flatten for a more functional approach:
Array.prototype.duplicate = function() {
return [].concat.apply([], this.map(function(v) {
return [v,v];
}));
};
console.log([1,2,3].duplicate()); //=> [1,1,2,2,3,3]
The simplest answer should be:
Array.prototype.duplicator=function () {
return this.concat(this).sort();
}
console.log([1,2,3,4,5].duplicator());//[1,1,2,2,3,3,4,4,5,5]
Because you're adding 2 at each iteration, thus stepping beyond the array boundaries. Try this instead:
for (var i=0; i<this.length; i++) {
a.push(this[i]);
a.push(this[i]);
}
You would want to place each value in i*2
and i*2+1
instead of i
and i+1
, and loop one step at a time:
Array.prototype.duplicator = function (){
var a = [];
for(var i = 0; i < this.length; i++){
a[i*2] = this[i];
a[i*2+1] = this[i];
}
return a;
};
Here's a fix:
Array.prototype.duplicator = function() {
var dup = [];
for (var i = 0; i < this.length; i++) {
dup[2 * i] = dup[2 * i + 1] = this[i];
}
return dup;
};
console.log([1,2,3,4,5].duplicator());
Array.prototype.duplicator = function () {
var a = [], k = 0;
for(var i=0;i<this.length;i++) {
a[k]=this[i];
k++;
a[k]=this[i];
k++;
}
return a;
};
duplicator = val => val.concat(val);
This works for me following the case in https://github./h5bp/Front-end-Developer-Interview-Questions/blob/master/src/questions/javascript-questions.md, where the desired result is [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]. Hope it works for you!
const duplicate = (...nums) => [].concat(...nums, ...nums);
console.log(duplicate([1, 2, 3, 4, 5]));
本文标签: javascriptWeird for loop behavior with duplicate array elementsStack Overflow
版权声明:本文标题:javascript - Weird for loop behavior with duplicate array elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745278188a2651298.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论