简体   繁体   中英

.push() value to JavaScript array (n) times using .fill()?

Is it possible to .push() a value to an array but replicate the pushed value n times without using a traditional loop to perform the replication? For instance using .fill() . The examples I have seen declare a new Array() with a length of n , and .fill() it with a value. However, I have not seen any examples dealing with .push() , so I'm not even sure it is possible.

Example of what I'm looking for:

var my_array = [];
for (var i = 0; i < 5; i++) {
    my_array.push(5);
};

Scenario:

I'm pulling values from three different arrays or objects to populate a single matrix that will be ran through a Munkres (Hungarian) algorithm, in order to avoid introducing another loop I would like to .push values to the matrix and use .fill() to repeat the value n times.

Example:

var s = […];
var a = […];
var p = […];

var matrix = [];
for (var i = 0; i < s.length; i++) {
    var preferences = [];
    for (var j = 0; j < p.length; j++ {
        var pid = p[j];
        for (var k = 0; k < a.length; k++ {
            if (pid == a[k]) {
                for (var l = 0; l < 5; l++) {  // <-- THIS.
                    preferences.push(a[k]);
                };
            };
        };
    };
    matrix.push(preferences);
};

您可以使用concatfill

preferences = preferences.concat(Array(5).fill(a[k]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM