JavaScript/array
来自康健生活
引言
特点
- 相同的数据类型
- 连续的线性内存
插入
查找
优化
二分法
O(log n)
删除
读取
遍历
判断
if (!this.length || this.length == 0) return this;
示例
去重
Array.prototype.uniq = function () {
if (!this.length || this.length == 0) return this;
var res = [], key, hasNaN = false, temp = {};
for (var i = 0 ; i < this.length; i++) {
if (typeof this[i] === 'object') {
res.push(this[i]);
} else if (this[i] != this[i]) { // 如果当前遍历元素是NaN
if (!hasNaN) {
res.push(this[i]);
hasNaN = true;
}
} else {
key = typeof(this[i]) + this[i];
if (!temp[key]) {
res.push(this[i]);
temp[key] = true;
}
}
}
return res;
}
Array.prototype.uniq = function () {
var res = [];
var flag = true;
this.forEach(function(x) {
if (res.indexOf(x) == -1) {
if (x != x) {
if (flag) {
res.push(x);
flag = false;
}
} else {
res.push(x);
}
}
})
return res;
}
清空数组
清空数组
相关问题
今天(2021-1-18)视频面试美团的一个岗位,笔试题是数组去重,如输入 [1, 2, 1, 1, '1'],输出 [1, 2, '1' ],看到题目第一眼我就想起使用 new Set,然后写了如下代码:
...new Set(array)
模板:Leftrightflex
接着试探着问面试官应该可以吧,面试官反应平平(我猜测他可能没用过这种方式,也不知道对不对),我也不好再尝试运行,虽然我知道可以解这道题,但是面试官不确定那我还是老老实实写其他代码吧,然后写了如下:
模板:Leftrightflex
面试官说你看对么,然后我看了一眼发现 Number 1 和 String 1 被等值了,毕竟是 map 是一个 object。我又尝试的问了一下,您觉的这样应该怎么处理呢,面试官说:“你在里面加一下判断,试着把 Number 1 和 String 1 区分开”,我想了一下没什么概念就试探着说其实这里可以用 Map 解决的,只需要把 var map = new Map() 就可以了(我感觉没有我反应快。。。,而且这判断怎么加。。。),面试官无感,我也就没再改代码,然后结束了。事后补全以下代码:
No categories