1. 扁平化数组
给定数组:[[1, 2, 3], 4, 5, 6, [[7]], []];
// 1、迭代递归法
function flatten(arr, newArray = []) {
for (let item of arr) {
if (Array.isArray(item)) {
flatten(item, newArray);
} else {
newArray.push(item);
}
}
return newArray;
}
var result = flatten(arr);
console.log(result);
// 2、reduce三句实现法(reduce法宝)
function threeDeal(arr) {
return arr.reduce((prev, curv) => {
return prev.concat(Array.isArray(curv) ? threeDeal(curv) : curv);
}, []);
}
console.log("***", threeDeal(arr));
// 曲线救国
function translateString(arr) {
let str = arr.toString();
console.log("___", str);
return str.split(",");
}
let value = translateString(arr);
console.log("+++", value);
2.判断回文字符串,如php\aaccaa\FFGGHH
// 判断回文字符串,如php\aaccaa\FFGGHH
function deal(str) {
if (typeof str == "string") {
console.log("**", str.split("").reverse());
return str.split("").reverse().join("") == str;
} else {
return false;
}
}
console.log(deal("php"));
3.js实现随机选取10-100之间10个数字,存入数组
function getRandom(start, end) {
// Math.random()*90最大不超90,最小大于0
// Math.random()*90 + 10最大不超100,最小大于10
// return Math.floor(Math.random() * 91) + 10;
return Math.floor(Math.random() * (end - start + 1)) + start;
}
function sort(a, b) {
return a - b; // 升序
}
arr = [];
for (var i = 0; i < 5; i++) {
arr.push(getRandom(1, 35));
}
console.log(arr);
arr.sort((a, b) => {
return a - b;
})
console.log(arr);