Javascript:
function array_pad ( input, pad_size, pad_value ) { // Pad array to the specified length with a value
//
// + original by: _argos
var pad = [], newArray = [], newLength, i=0;
if ( input instanceof Array && !isNaN ( pad_size ) ) {
newLength = ( ( pad_size < 0 ) ? ( pad_size * -1 ) : pad_size );
if ( newLength > input.length ) {
for ( i = 0; i < ( newLength - input.length ); i++ ) { newArray [ i ] = pad_value; }
pad = ( ( pad_size < 0 ) ? newArray.concat ( input ) : input.concat ( newArray ) );
} else {
pad = input;
}
}
return pad;
}
Примеры:
array_pad([ 7, 8, 9 ], 2, 'a');
[ 7, 8, 9]
array_pad([ 7, 8, 9 ], 5, 'a');
[ 7, 8, 9, 'a', 'a']
array_pad([ 7, 8, 9 ], 5, 2);
[ 7, 8, 9, 2, 2]
array_pad([ 7, 8, 9 ], -5, 'a');
[ 'a', 'a', 7, 8, 9 ]
|