在JavaScript中将for循环转换为while循环 [英] Convert for loop to a while loop in JavaScript

查看:224
本文介绍了在JavaScript中将for循环转换为while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将以下使用for循环的JS代码转换为while循环和/或do-while循环.

I've been trying to convert the following JS code that uses a for loop to a while loop and/or do-while loop.

var unique = function(array) 
{
  var newArray = []
  array.sort()
  for(var x in array) if(array[x] != array[x-1]) newArray.push(array[x])
  return newArray
}

该代码假定仅返回重复的名称数组中的不同名称.我一直在尝试转换for循环,但到目前为止,使用此方法我一直遇到问题:

The code is suppose to return only distinct names from an array of names that repeat. I've been trying to convert the for loop but so far I've been running into problems using this:

do
{
    newArray.push(array[x])
}
while(array[x] != array[x-1])
return newArray;

有人可以帮助我吗?谢谢!

Can anyone help me? Thanks!

推荐答案

您非常亲密.以下内容保留了原始顺序:

You're very close. The following preserves the original sequence:

function getUnique(array) {
  var newArray = array.slice(); // copy original
  var i = newArray.length - 1;

  do {
      if (newArray[i] == newArray[--i]) {
        newArray.splice(i, 1);
      }
  } while(i)

  return newArray;
}

请注意,以上假定了一个已排序的连续数组(没有丢失的成员).如果不确定,请在 do..while 循环之前对 newArray 进行排序,然后压缩它使其连续.

Note that the above assumes a sorted, contiguous array (no missing members). If you can't be sure of that, sort newArray before the do..while loop and maybe compact it to make it contiguous.

这篇关于在JavaScript中将for循环转换为while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆