js数组去重利用set

JavaScript08

js数组去重利用set,第1张

const nums = [1,2,3,4,3,2,1]

uniq1 = [...new Set(nums)]

uniq2 = Array.from(new Set(nums))

定义:新数据结构Set,类似于数组,但成员值不重复

使用: new Set()

ps:New Set() 接受一个数组或类数组对象,在Set内部, NAN相等,两个对象不等,可以用length检测,可以用for...of遍历

size:返回值的个数

add(val):添加值,返回set结构;

delete(val):删除值,返回布尔值

has(val):是否包含,返回布尔值

clear():清除所有成员,无返回值

与set类似,也是不重复值的集合

与set的区别:1.weakset 成员只能是对象,对象都是弱引用,垃圾回收机制不考虑,不可遍历

定义:类似于对象,也是键值dui的集合,但键可以是各种类型(键可以为对象),两个键严格相等才为同一个键。

Var m = new Map(), o = {1:2}

m.set(o, ‘hi’)

m.get(o)

m.has(o) //只有对同一个对象的引用才是同一个键

size:返回值的个数

set(key, val):添加值,返回Map结构;

Get(key): 获取值,返回val

Has(key):是否包含,返回布尔值

Delete(key):删除值,返回布尔值

Clear():清除所有成员,无返回值

定义:把泪数组对象和有iterator接口的对象(Set Map Array)转化为数组

使用:Array.from(arrayLike[, mapFn[, thisArg]]) 参数:类数组,处理函数map,map中的this指向的对象

Array.from([1, 2, 3, 4, 5], (n) =>n + 1) // 每个值都加一

const map = new Map()

map.set(‘k1’, 1)

map.set(‘k2’, 2)

Const a = Array.from(map) // [[‘k1’,1], [‘k2’, 2]]

const set1 = new Set()

Set1.add(1).add(2).add(3)

Var a = Array.from(set1) // [1,2,3]

console.log('%s', Array.from('hello world’)) //["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

console.log('%s', Array.from('\u767d\u8272\u7684\u6d77’)) //["白", "色", "的", "海"]

var a = {0:1, 2:3, 4:5, length: 5}var b = {0:1, 2:3, 4:5, length: 3}

Array.from(a) // [1,undefined,3,undefined,4]

Array.from(b) // [1,undefined,3]

js动态添加数组可以按下面的步骤:

1、在数组的开头添加新元素 - unshift()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add elements to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.unshift("Lemon","Pineapple")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

<p><b>Note:</b>The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p>

</body>

</html>

测试结果:

Lemon,Pineapple,Banana,Orange,Apple,Mango

2、在数组的第2位置添加一个元素 - splice()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add elements to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.splice(2,0,"Lemon","Kiwi")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

</body>

</html> 

测试结果:

Banana,Orange,Lemon,Kiwi,Apple,Mango

3、数组的末尾添加新的元素 - push()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add a new element to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"]

function myFunction()

{

fruits.push("Kiwi")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

</body>

</html>

测试结果:

Banana,Orange,Apple,Mango,Kiwi