如何在第一个重复值后使用 JavaScript 循环返回重复值的空格

我有一个数组:


var a = ['green','green','green','yellow','yellow','yellow','white','blue']

我将循环显示数组,输出应该是:


green



yellow



white

blue

它应该有空间。例如 3 个绿色,它应该显示 1 个绿色,接下来是 2 个空格或换行符


紫衣仙女
浏览 86回答 2
2回答

RISEBY

您可以使用 aset来实现:var a = ['green','green','green','yellow','yellow','yellow','white','blue'];let set = new Set();for(let i = 0; i < a.length; i++){&nbsp; &nbsp; &nbsp;if(!set.has(a[i])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(a[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set.add(a[i]);&nbsp; &nbsp; &nbsp;}else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(" ");&nbsp; &nbsp; &nbsp;}}

胡说叔叔

您可以为最后一个值取一个变量并检查。var array = ['green', 'green', 'green', 'yellow', 'yellow', 'yellow', 'white', 'blue'],&nbsp; &nbsp; last;&nbsp; &nbsp;&nbsp;for (const value of array) console.log(value === last ? '' : last = value);.as-console-wrapper { max-height: 100% !important; top: 0; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript