是否有在JavaScript中创建填充数组的快捷方式? [英] Is there a shortcut to create padded array in JavaScript?
本文介绍了是否有在JavaScript中创建填充数组的快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个javascript:
I have this javascript:
function padded_array(k, value){
var a = [];
a[k] = value;
return a;
}
padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello']
是否可以缩短函数体内的代码?
Is it possible to shorten the code in the function body?
推荐答案
所有来到这里的Google员工-您可能正在寻找它:
for all the googlers coming here - you're probably looking for this:
var pad_array = function(arr,len,fill) {
return arr.concat(Array(len).fill(fill)).slice(0,len);
}
这篇关于是否有在JavaScript中创建填充数组的快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文