JavaScript 算法 - 从数组中移除负数


给定具有多个值的数组 X(例如 [-3,5,1,3,2,10]),我们需要编写一个函数来移除数组中的任何负值。

一旦函数完成执行,数组应仅由正数组成。我们需要这样做,而无需创建一个临时数组,且仅使用弹出方法来移除数组中的任何值。

示例

以下是代码 −

// strip all negatives off the end
while (x.length && x[x.length - 1] < 0) {
   x.pop();
}
for (var i = x.length - 1; i >= 0; i--) {
   if (x[i] < 0) {
      // replace this element with the last element (guaranteed to be positive)
      x[i] = x[x.length - 1];
      x.pop();
   }
}

输出

代码将在控制台中产生以下输出 −

[ 1, 8, 9 ]

更新于: 01-Oct-2020

220 次浏览

开启您的事业

完成课程并获得认证

开始
广告