-1

抱歉,如果这是一个已问/已回答的问题,但我进行了一般搜索,但找不到我正在寻找的结果。

假设我有一个数组,但我不知道它的长度,无论出于何种原因。我想将项目插入到数组中的确切位置(在本例中为中心)

出于这个问题的目的,我将提供数组以及如何让输出正确读取..

function insertIntoMiddle(array, item) {
    array.splice(4, 2, item);
    return array.sort();
}


const items = insertIntoMiddle([1, 3], 2);
console.log(insertIntoMiddle([1, 3], 2), '<-- should be [1 , 2 , 3]');
console.log(insertIntoMiddle([1, 3, 7, 9], 5), '<-- should be [1, 3, 5, 7, 9]');

我们得到以下输出:

 [1, 2, 3] <-- should be [1 , 2 , 3] 
 [1, 3, 5, 7, 9] <-- should be [1, 3, 5, 7, 9]

应该是这样。但我的问题是,如果出于某种原因,说它是一个数据库,它被读入一个数组进行操作,并且随着时间的推移数据库已经增长。我们不知道数组有多长..但是我们仍然想插入到数组的确切中间..如何去做呢?

4

2 回答 2

0

您可以使用两个指针,第一个用 +2 移动,第二个用 +1 移动,直到结束。

当第一个在末尾时,第二个将在中间。

在第二个指针的位置插入项目。

function insertIntoMiddle(array, item) {
  let i = 0;
  let j = 0;
  while (array[i]) {
    i += 2;
    j++;
  }
  array.splice(j, 0, item);
  return array;
}

console.log(insertIntoMiddle([1, 3, 7, 9], 5));
console.log(insertIntoMiddle([1, 3], 2));

于 2019-10-14T16:48:53.010 回答
0

你可以用一半的长度拼接它。

function insertIntoMiddle(array, item) {
    array.splice(array.length >> 1, 0, item);
    return array
}

console.log(...insertIntoMiddle([1, 3], 2));
console.log(...insertIntoMiddle([1, 3, 7, 9], 5));

于 2019-10-14T16:44:57.430 回答