JavaScript/array:修订间差异
来自康健生活
| 第3行: | 第3行: | ||
* 相同的数据类型 | * 相同的数据类型 | ||
* 连续的线性内存 | * 连续的线性内存 | ||
== 插入 == | |||
== 寻找 == | |||
== 删除 == | |||
== 读取 == | |||
== 遍历 == | == 遍历 == | ||
2020年6月24日 (三) 06:31的版本
引言
特点
- 相同的数据类型
- 连续的线性内存
插入
寻找
删除
读取
遍历
判断
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;
}
No categories