最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Weird for loop behavior with duplicate array elements - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Feb 2, 2013 at 23:18 Boaz 20.2k9 gold badges66 silver badges72 bronze badges asked Feb 2, 2013 at 23:02 norbi123norbi123 411 silver badge8 bronze badges
Add a ment  | 

9 Answers 9

Reset to default 5
Array.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]));
发布评论

评论列表(0)

  1. 暂无评论