Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - 将值添加到数组的最有效方法(Most efficient way to prepend a value to an array)

Assuming I have an array that has a size of N (where N > 0 ), is there a more efficient way of prepending to the array that would not require O(N + 1) steps?(假设我有一个大小为N (其中N > 0 )的数组,是否有一种更有效的方法可以预先添加到不需要O(N + 1)步的数组?)

In code, essentially, what I currently am doing is(在代码中,基本上,我目前正在做的是)

function prependArray(value, oldArray) {
  var newArray = new Array(value);

  for(var i = 0; i < oldArray.length; ++i) {
    newArray.push(oldArray[i]);
  }

  return newArray;
}
  ask by samccone translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure about more efficient in terms of big-O but certainly using the unshift method is more concise:(我不确定在big-O方面效率更高,但肯定使用unshift方法更简洁:)

var a = [1, 2, 3, 4];
a.unshift(0);
a; // => [0, 1, 2, 3, 4]

[Edit]([编辑])

This jsPerf benchmark shows that unshift is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place.(这jsPerf基准表明, unshift是体面的至少几个浏览器速度更快,无论可能不同的大O性能,如果您没有问题修改就地数组。)

If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:(如果你真的无法改变原始数组,那么你会做类似下面的代码片段,它似乎没有比你的解决方案快得多:)
a.slice().unshift(0); // Use "slice" to avoid mutating "a".

[Edit 2]([编辑2])

For completeness, the following function can be used instead of OP's example prependArray(...) to take advantage of the Array unshift(...) method:(为了完整性,可以使用以下函数代替OP的示例prependArray(...)来利用Array unshift(...)方法:)

function prepend(value, array) {
  var newArray = array.slice();
  newArray.unshift(value);
  return newArray;
}

var x = [1, 2, 3];
var y = prepend(0, x);
y; // => [0, 1, 2, 3];
x; // => [1, 2, 3];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...