Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit def2e95

Browse files
修订JavaScript专题之数组去重
1 parent 3a6db9f commit def2e95

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

‎articles/专题系列文章/JavaScript专题之数组去重.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,22 @@ function unique(array) {
235235
console.log(unique(array)); // [1, 2, "1"]
236236
```
237237

238+
然而,即便如此,我们依然无法正确区分出两个对象,比如 {value: 1} 和 {value: 2},因为 `typeof item + item` 的结果都会是 `object[object Object]`,不过我们可以使用 JSON.stringify 将对象序列化:
239+
240+
```js
241+
var array = [{value: 1}, {value: 1}, {value: 2}];
242+
243+
function unique(array) {
244+
var obj = {};
245+
return array.filter(function(item, index, array){
246+
console.log(typeof item + JSON.stringify(item))
247+
return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true)
248+
})
249+
}
250+
251+
console.log(unique(array)); // [{value: 1}, {value: 2}]
252+
```
253+
238254
## ES6
239255

240256
随着 ES6 的到来,去重的方法又有了进展,比如我们可以使用 Set 和 Map 数据结构,以 Set 为例,ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /