数组扁平化(又称数组降维)
Array.flat()
const test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// flat不传参数时,默认扁平化一层
test.flat()
// ["a", "b", "c", "d", ["e", ["f"]], "g"]
// flat传入一个整数参数,整数即扁平化的层数
test.flat(2)
// ["a", "b", "c", "d", "e", ["f"], "g"]
// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
test.flat(Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]
// 传入 <=0 的整数将返回原数组,不扁平化
test.flat(0)
test.flat(-1)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 如果原数组有空位,flat()方法会跳过空位。
["a", "b", "c", "d",,].flat()
// ["a", "b", "c", "d"]
使用reduce方法
function flat(arr, depth = 1) {
return depth > 0
? arr.reduce((acc, cur) => {
if(Array.isArray(cur)) {
return [...acc, ...flat(cur, depth-1)]
}
return [...acc, cur]
} , [])
: arr
}
// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 不传参数时,默认扁平化一层
flat(test)
// ["a", "b", "c", "d", ["e", ["f"]], "g"]
// 传入一个整数参数,整数即扁平化的层数
flat(test, 2)
// ["a", "b", "c", "d", "e", ["f"], "g"]
// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
flat(test, Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]
// 传入 <=0 的整数将返回原数组,不扁平化
flat(test, 0)
flat(test, -10)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];
// 如果原数组有空位,flat()方法会跳过空位。
var arr = ["a", "b", "c", "d",,]
flat(arr)
// ["a", "b", "c", "d"]
栈
function flat(arr, depth = 1) {
return depth > 0
? arr.reduce((acc, cur) => {
if(Array.isArray(cur)) {
return [...acc, ...flat(cur, depth-1)]
}
return [...acc, cur]
} , [])
: arr
}
// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 不传参数时,默认扁平化一层
flat(test)
// ["a", "b", "c", "d", ["e", ["f"]], "g"]
// 传入一个整数参数,整数即扁平化的层数
flat(test, 2)
// ["a", "b", "c", "d", "e", ["f"], "g"]
// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
flat(test, Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]
// 传入 <=0 的整数将返回原数组,不扁平化
flat(test, 0)
flat(test, -10)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];
// 如果原数组有空位,flat()方法会跳过空位。
var arr = ["a", "b", "c", "d",,]
flat(arr)
// ["a", "b", "c", "d"]
数组去重
set (ES6)
function unique(arr) {
return Array.from(new Set(arr))
}
// 或者
var unique = arr => [...new Set(arr)]
reduce
function unique (arr) {
return arr.sort().reduce((acc, cur) => {
if (acc.length === 0 || acc[acc.length - 1] !== cur) {
acc.push(cur);
}
return acc
}, [])}
;
filter
function unique(arr) {
return arr.filter( (element, index, array) => {
return array.indexOf(element) === index
})
}
去掉字符串中的空格
trim(str){
if (!str) {
return '';
}
return str.replace(/\s*/g,'');
}
判断两个对象是否相同
isObjectValueEqual(x, y) {
// 指向同一内存时
if (x === y) {
return true;
} else if (
typeof x == 'object' &&
x != null &&
typeof y == 'object' && y != null
) {
if (Object.keys(x).length != Object.keys(y).length) return false;
for (var prop in x) {
if (y.hasOwnProperty(prop)) {
if (!this.isObjectValueEqual(x[prop], y[prop])) return false;
} else return false;
}
return true;
} else return false;
}