Javascript 如何将字符串输入到数组中的给定位置?

Javascript 如何将字符串输入到数组中的给定位置?,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,条件是我必须输入一个字符串到数组中的给定位置 这样,所有前置位置(如果不存在)都应设置为空字符串 榜样 var array = []; // now I want to enter a string 'hello' at index 2 现在,阵列应该如下所示: array = [ '','','hello']; //now lets say I want to enter a string 'world' at index 4 因此,阵列应为: array = [ '','','hello

条件是我必须输入一个字符串到数组中的给定位置 这样,所有前置位置(如果不存在)都应设置为空字符串

榜样

var array = []; // now I want to enter a string 'hello' at index 2
现在,阵列应该如下所示:

array = [ '','','hello']; //now lets say I want to enter a string 'world' at index 4
因此,阵列应为:

array = [ '','','hello','','world'];
有办法做到这一点吗? 或者我是否有更好的选项来输入字符串及其位置


请告诉我……)

像这样的事情应该可以奏效。该函数接受三个参数:目标数组、索引(基于0)和值。只需从数组的结尾到新位置进行迭代,并将
添加到每个条目中,然后在循环之后,将所需字符串排队。这是我的建议

a=['','Hello'];
函数addStringAtPosition(
阵列,
钥匙
价值
) {
for(设i=array.length;i
  • 首先找出需要添加多少其他元素“”
  • 将这些新元素推送到数组中
  • 在末尾按下所需的值
  • PS:假设索引始终高于数组长度。我们也可以为这些情况增加条件

    const insert=(arr、value、index)=>{
    arr.push(…新数组(索引-arr.length).fill(“”);
    arr.push(值);
    返回arr;
    };
    常量数组=[];
    插入(数组“hello”,2);
    console.log(数组);
    插入(数组,“世界”,4);
    
    console.log(数组)这似乎是一个奇怪的要求。你介意解释一下你将如何使用这个吗?可能有更好的方法来实现你的目标。