如何添加到一个数组在Javascript中插入一个数字和数字后移动到右边

How to add to an array in Javascript by inserting a number and moving the numbers after to the right

本文关键字:数字 一个 何添加 移动 右边 插入 数组 Javascript 添加      更新时间:2023-09-26

我试图插入一个值到数组中。我没有改变数组的大小。我所要做的就是插入一个值,然后使用以下算法将插入后的所有数字向右移动:

  1. 转到数组的最后一个元素n = (length-1)

  2. 如果不是传递的索引(n> index),则将其值设置为前一个元素的值A(n) = A(n-1)

  3. 如果是传递的索引(n = index),则设置为传递的值A(n) = value,退出

  4. 左移一个元素n = n-1

  5. 重复步骤2、3、4

我该怎么做?此外,我不能使用任何内置数组函数。下面是我的Javascript代码的一个例子:

var array = [];
for(var i=1; i<=1000; i++) {
array.push(Math.round(Math.random()*100));
}
function InsertIntoArray(array,index,number){
var numCount = 0
var move = 0 ;
for(var move = array.length - 1; move > index; move--)
{
  if (move > index)
  {
      array[i] = array[i-1];
      numCount ++;
  }
  else (move == index)
  {
      array[index] = number;
      numCount++;
      break;
  }
}
console.log(move);
console.log(numCount);
console.log(array);
}
console.log(array);
InsertIntoArray(array, 1, 11);

您非常接近,但做的日志比需要的多。希望这些注释是足够的:

// Just use simple test cases initially
var array = [0,1,2,3];
// The original function had some unused and pointless variables,
// they're removed
function insertIntoArray(array, index, value){
  
  // Don't allow index to be greater than length - 1
  if (index > array.length - 1) return;
  
  // Loop until the required index is reached, shifting
  // values to the next higher index
  for(var move = array.length - 1; move > index; move--) {
    array[move] = array[move - 1];
  }
  
  // Must now have reached required index and have shifted
  // values, so just insert
  array[index] = value;
}
// Original array
document.write(array + '<br>');
// Do insert
insertIntoArray(array, 2, 15);
// Modified array
document.write(array);

注意,你可以有稀疏数组,上面的代码将在这样的数组中创建新的元素,所以它们不再是稀疏的。此外,对于大型数组,它将非常低效,Barmar的splice + slice答案在这方面可能更好,尽管它确实改变了长度

您可以在index处将数组分为左数组和右数组,将项添加到左数组中,并从右数组中删除最后一项。然后组合两个数组:

function InsertIntoArray(array,index,number){
    var leftArray = array.slice(0, index);
    var rightArray = array.slice(index, array.length - 1);
    leftArray.push(number);
    return leftArray.concat(rightArray);
}
<<p> 小提琴例子/strong>。注意,使用return是为了改变给定数组的值,而不是本地array值。简单地改变函数中的array不会改变全局的array变量

循环的问题是您使用的是array[i] = array[i-1],但循环中的索引变量是move,而不是i

您不需要在循环中执行if。只要在循环完成后插入新元素即可。你在else中也有一个语法错误——你没有在else之后放一个测试,它自动与if相反。

function InsertIntoArray(array, index, number) {
  // Move all the elements after index up by 1
  for (var move = array.length - 1; move > index; move--) {
    array[move] = array[move - 1];
  }
  // Insert the new element
  array[index] = number;
}
var array = [];
for (var i = 1; i <= 30; i++) {
  array.push(i);
}
document.getElementById("before").textContent = JSON.stringify(array);
InsertIntoArray(array, 1, 11);
document.getElementById("results").textContent = JSON.stringify(array);
<b>Before:</b> 
<div id="before"></div>
<b>After:</b> 
<div id="results"></div>

相关文章: