JavaScript/array:修订间差异
来自康健生活
| 第15行: | 第15行: | ||
== 插入 == | == 插入 == | ||
== 合并 == | == 合并 == | ||
<syntaxhighlight lang="javascript"> | 合并两个数组。 | ||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
</syntaxhighlight> | const source = [1, 2]; | ||
const target = [3, 4]; | |||
const lastItem = source.push.apply(source, target || []); | |||
console.log(lastItem); | |||
console.log(source);</syntaxhighlight>|{{consoleout|<pre>4 | |||
[1, 2, 3, 4] | |||
</pre>}}}} | |||
== 查找 == | == 查找 == | ||
2022年1月7日 (五) 12:19的版本
引言
特点
- 相同的数据类型
- 连续的线性内存
方法
| find | 示例 | 示例 |
| 示例 | 示例 | 示例 |
| 示例 | 示例 | 示例 |
插入
合并
合并两个数组。 模板:Leftrightflex
查找
优化
二分法
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;
}
数组拍平
样本。
const sample = [1, 2, [3, 4, 5, [6, 7, 8], 9], 10, [11, 12]];
递归。 模板:Leftrightflex
reduce。 模板:Leftrightflex
flat。 模板:Leftrightflex
扩展运算符。有待优化。 模板:Leftrightflex
toString。 模板:Leftrightflex
apply。 模板:Leftrightflex
清空数组
清空数组
关键词:引用
相关问题
今天(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