简体   繁体   English

无需 unshift 方法即可将项目添加到数组开头的函数

[英]function to add item to beginning of an array without unshift method

I am trying to implement a function to add an item to the beginning of an array without using the unshift or splice methods, just array.length.我正在尝试实现一个函数来将一个项目添加到数组的开头,而不使用 unshift 或拼接方法,只是 array.length。 Everything I do so far just overwrites what is already existing at index 0. Any help would be appreciated!到目前为止我所做的一切都只是覆盖索引 0 处已经存在的内容。任何帮助将不胜感激!

LetsUnshift = function(array) { 
 for (var i = array.length - 1; i >0; i--) {
    array[i +1] = array[i];
 }
 array[0] = item;
};

Keeping the same reference, you could use ES 6's Array.prototype.copyWithin保持相同的引用,你可以使用ES 6 的Array.prototype.copyWithin

var arr = ['b', 'c', 'd'],
    x = 'a';
++arr.length;
arr.copyWithin(1, 0);
arr[0] = x;

arr; // ["a", "b", "c", "d"]

You could reverse twice,你可以反转两次,

var arr = ['b', 'c', 'd'];
arr.reverse().push('a');
arr.reverse();

arr; // ["a", "b", "c", "d"]

You could re-push the whole thing,你可以重新推动整个事情,

var arr = ['b', 'c', 'd'],
    a2 = arr.slice();
arr.length = 0;
arr.push('a');
Array.prototype.push.apply(arr, a2);

arr; // ["a", "b", "c", "d"]

You could iterate with while , similar to your for你可以迭代while ,类似于你的for

var arr = ['b', 'c', 'd'],
    i = arr.length;
while (i-- > 0)
    arr[i + 1] = arr[i];
arr[0] = 'a';

arr; // ["a", "b", "c", "d"]

If your goal is to create a new reference you could re-write either of those last two, eg如果你的目标是创建一个新的参考,你可以重写最后两个中的任何一个,例如

var arr = ['b', 'c', 'd'],
    a2 = ['a'];
Array.prototype.push.apply(a2, arr);

a2; // ["a", "b", "c", "d"]

If we're just code-golfing,如果我们只是打代码,

var arr = ['b', 'c', 'd'],
    a2 = Array.bind(null, 'a').apply(null, arr);

a2; // ["a", "b", "c", "d"]

This should work:这应该有效:

 var LetsUnshift = function(array, item) { 
      for (var i = array.length - 1; i >=0; i--) {
         array[i +1] = array[i];
      }
      array[0] = item;
 };

The issue with your code is the condition i>0 , which prevents the first element from being shifted to the right.您的代码的问题是条件i>0 ,它阻止第一个元素向右移动。

letsUnshift = function(array, itemToAdd) { 
  return array.reduce(function(newArray, value){
    newArray.push(value);
    return newArray;
  }, [itemToAdd]);
};
letsUnshift([2,3,4], 1); //returns [1,2,3,4] and doesn't modify original array

Just called the function instead and start it from arr.length-1 down to >= 0 as suggested in another answer只是调用了该函数,然后按照另一个答案中的建议从arr.length-1开始到>= 0

 var item = 15, i, arr = [11, 23, 33, 54, 17, 89]; LetsUnshift(arr); function LetsUnshift(arr) { for (i = arr.length-1; i >= 0; --i) { arr[i + 1] = arr[i]; } arr[0] = item; }; console.log(arr); //OUTPUT: [15, 11, 23, 33, 54, 17, 89]

const array=[1,2,3]
const target=3

function addElementAtStarting(array, target){
    return [target, ...array]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM