# 数组扩展

``````function *g () {
console.log(1)
yield 'one'
console.log(2)
yield 'two'
}

const gg = g()
gg.next()

setTimeout(function(){
gg.next()
},1000)``````

``````let set = new Set([1,2,5,3,4]) // 返回一个数组
console.log(set)
let arr = [...set] // 展开为数组``````

`Set` 里的元素不可以重复，所以可以用它来去重！！！

Set 对象允许你存储任何类型的唯一值，无论是原始值或者是对象引用。

``````const set1 = new Set([1, 2, 3, 4, 5]);

console.log(set1.has(1));
// expected output: true

console.log(set1.has(5));
// expected output: true

console.log(set1.has(6));
// expected output: false``````
``new Set([iterable]);``

`iterable`

Tips：利用循环，获取10个整数

``````function getRandomInt(max) {
return Math.floor(Math.random()* Math.floor(max));
}
let numberArr = []
for(let i=0;i<=9;i++) {
numberArr.push(getRandomInt(100))
}
// console.log(numberArr)

function newSort(...arr) {
let temArr = []
let temMax = 0
let argument = [...arguments[0]]
console.log(argument)
let length = argument.length
for(let i=0;i<length;i++) {
for(let j=0;j<length-i-1;j++) {
temMax = Math.max(argument[j],argument[j+1])
}
temArr.push(temMax)
}
console.log(temArr)
numberArr.length = 0
numberArr = [...temArr]
}
console.log(numberArr)
newSort(numberArr)
console.log(numberArr)``````

### 新的方法

#### Array.from(obj)

`ArrayLike`对象或者`Iterable`对象转换为一个`Array`

``````const obj = {
0: 1,
1: 'kangkang',
2: false,
length:2
}
// 属性名必须是数字或者字符形式的数字
console.log(Array.from(obj))

//（2)?[1, "kangkang"]0: 11: "kangkang"length: 2__proto__: Array(0)

console.log(Array.from(obj,item => item*2))

//接受第二个参数对对象里每个值进行运算！``````

#### Array.of()

``````let arr = Array.of("1",2,"adf",false)
// (4)?["1", 2, "adf", false]``````

#### fill()

``````let arr = new Array(10).fill(0)
// [0,0,0.....]
console.log([1,2,3].fill(0)) // 会覆盖掉原先的数据
let arr = new Array(10).fill(0,0,5)// 指定开始位置和结束位置（不包括5）``````

#### Array.includes()

``````let arr = [1,2,3,234,32,42]
console.log(arr.includes(234))/true``````

#### keys

``````let arr = [1,23,34]
let keys = arr.keys()
for (let i of keys) {
console.log(i)
} // 0    1   2``````

#### values

``````let arr = [1,23,34]
let values = arr.values()
for (let i of values) {
console.log(i)
} // 1  23  34``````

#### entries

``````let arr = [1,23,34]
let entries = arr.entries()
for (let i of entries) {
console.log(i)
}
// [0, 1]
// [1, 23]
// [2, 34]

for (let [j,v] of arr.entries()) {
console.log(j,v)
}
// 0 1
// 1 23
// 2 34``````

#### find

``````const res = [1,2,3,23,34,45].find((value,index,arr)=> {
return value % 3 ===0
})
console.log(res) // 3``````

#### findIndex

``````const res = [1,2,3,23,34,45].findIndex((value,index,arr)=> {
return value % 3 ===0
})
console.log(res) // 2``````

`arr.indexOf(NaN)` 无法判断 ，但是

``````const res = [1,2,3,23,34,45,NaN].findIndex((value,index,arr)=> Number.isNaN(value))
console.log(res) // 6``````

(0)
(0)

0条

© 2014 mamicode.com 版权所有 京ICP备13008772号-2