简体   繁体   中英

pad javascript array with value until length is evenly divisible by three

I am given a number of arrays of varying length. I'd like to pad these arrays (value of padding element can be 0 ) so that the length is evenly divisible by three (I need to create three subarrays of equal length for each array i'm given).

Here's my intended, unsuccessful code with a while loop and an array push that should increment len until len % 3 === 0 :

function fillArray(value, arr) {
  var len = arr.length;
  while (len % 3 !== 0) {
    arr.push(value);
  }
  return arr;
}

For example, if given an array as follows

[1,2,3,4,5,6,7,8,9,10]

I'll want to pad (with 0 ) until the length is divisible by three:

[1,2,3,4,5,6,7,8,9,10,0,0]

thanks for your help.

You're not updating your len variable after the initialization.

Instead, use the length property directly:

 function fillArray(value, arr) { while (arr.length % 3 !== 0) { arr.push(value); } return arr; } document.write(fillArray(0, [1,2,3,4,5,6,7,8,9,10])); 

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