在特定情况下将数据推送到数组中

Push data in array in specific case

我正在尝试将数据推送到具有特定索引的数组中。

起初,我有一个空数组:[]

从web socket(number)接收数据后,例子number = 4,我想把这个number压入Array的第4位

输出:[null,null,null,null,4]

或者我不能输入 null 以外的任何内容,例如:“-”

新输出:[-,-,-,-,4]

从网络套接字接收到第二个数据后,示例编号= 2。

新输出:[-,-,2,-,4]

我试过这个:

let tArray = [];
for(let i=0; i<number + 1; i++){
   if(i == number){
      tArray[i].push(number);
   }
   if(!tArray[i]){
      tArray[i].push("-");
   }
}

这应该适合你:

const tArray = [];
if (tArray.length < number+1) {
  while (tArray.length < number+1) {
    tArray.push('-');
  }
}
tArray[number] = number;

如果您更改 tArray.push() 中的 tArray[i].push() 部分,您的代码也应该没问题。

您可以创建一个所需大小的数组,用 "-" 填充它,然后在您的特定位置设置数字:

const number = 2, maxSize = 4;

const tArray = new Array(maxSize).fill('-');
tArray[number] = number;

console.log(tArray);

创建一个预定义大小的数组,然后将数据放入数组中

let data = 4;
let size = 10; // as much as you like

let array = new Array(size).fill('-');

// now when the data comes from the web socket you can simply put inside the array

array[data - 1] = data;
console.log(array)

Concat the current array(tArray) with a new Array 长度等于:

您的电话号码(和职位)- 当前 array length + 1

这个有 仅当当前数组 (tArray) 不够大时才会发生

var tArray = [];
var pushIntoTarray = function (number) {
    if (tArray.length < number) {
        tArray = tArray.concat(new Array(number - tArray.length + 1).fill("-"));
    }
    tArray[number] = number;
    console.log(tArray);
}
pushIntoTarray(4);
pushIntoTarray(2);
pushIntoTarray(1);
pushIntoTarray(10);