How to extend an existing JavaScript array with another array, without creating a new array

后端 未结 16 1882
深忆病人
深忆病人 2020-11-22 07:38

There doesn\'t seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python\'s extend method.

I want to achieve th

16条回答
  •  情歌与酒
    2020-11-22 08:11

    You can create a polyfill for extend as I have below. It will add to the array; in-place and return itself, so that you can chain other methods.

    if (Array.prototype.extend === undefined) {
      Array.prototype.extend = function(other) {
        this.push.apply(this, arguments.length > 1 ? arguments : other);
        return this;
      };
    }
    
    function print() {
      document.body.innerHTML += [].map.call(arguments, function(item) {
        return typeof item === 'object' ? JSON.stringify(item) : item;
      }).join(' ') + '\n';
    }
    document.body.innerHTML = '';
    
    var a = [1, 2, 3];
    var b = [4, 5, 6];
    
    print('Concat');
    print('(1)', a.concat(b));
    print('(2)', a.concat(b));
    print('(3)', a.concat(4, 5, 6));
    
    print('\nExtend');
    print('(1)', a.extend(b));
    print('(2)', a.extend(b));
    print('(3)', a.extend(4, 5, 6));
    body {
      font-family: monospace;
      white-space: pre;
    }

提交回复
热议问题