判断是否为空:
字符串和数字互转
- 数字转字符串:数字.toString()
- 字符串转数字:parseInt(字符串)
生成指定长度随机字符串
//生成指定长度随机字符串
generateRandomStr(strLength = 4) {
let code = '';
const chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const charsArr = chars.split('');
for (let i = 0; i < strLength; i++) {
const num = Math.floor(Math.random() * charsArr.length);
code += charsArr[num];
}
return code;
},
JavaScript随机获取数组Array中的值:
let colors = ["orange","red","blue","yellow"];
let color = colors[Math.floor(Math.random()*colors.length)];
js 解析出rgba字符串里的各个值
mounted() {
let color = "rgba(19, 206, 102, 0.8)";
console.log("R this.rgbaNum(color, 0):", this.rgbaNum(color, 0));
console.log("G this.rgbaNum(color, 1):", this.rgbaNum(color, 1));
console.log("B this.rgbaNum(color, 2):", this.rgbaNum(color, 2));
console.log("A this.rgbaNum(color, 3):", this.rgbaNum(color, 3));
},
methods: {
rgbaNum(rgba, index) {
return rgba.match(/(\d(\.\d+)?)+/g)[index];
}
}
改变鼠标样式
document.getElementById("app").style.cursor = "default";
div跟随鼠标移动
<template>
<div
style="width: 50px; height: 50px; background-color: red; position: fixed"
:style="{ left: left, top: top }"
></div>
</template>
<script>
export default {
data() {
return {
left: "",
top: "",
};
},
computed: {},
created() {},
mounted() {
document.addEventListener("mousemove", (e) => {
this.left = e.clientX + 40 + "px";
this.top = e.clientY - 50 + "px";
});
},
};
</script>
根据输入的数字,返回比这个数字小1的字符串数组
如:输入15,返回['00','01',...,'14','15']。输入8,返回['00','01',...,'07','08']
test2(value) {
let arr = [];
let a = parseInt(value);
for (let i = 0; i <= a; i++) {
arr.push(i);
}
let c = arr.map((d) => {
if (d < 10) return '0' + d;
else return d.toString();
});
console.log(c);
return c;
},
parentId形式数据转children形式-toTreeData()
/**
* parentId形式数据转children形式
* @param option
* @returns {[]} 转换后的数据
*/
export function toTreeData(option) {
// 兼容旧版
if (Array.isArray(option)) {
option = {
data: arguments[0],
idField: arguments[1],
parentIdField: arguments[2],
childrenField: arguments[3],
parentId: arguments[4],
addParentIds: arguments[5],
parentIdsField: arguments[6],
parentIds: arguments[7]
};
}
const data = option.data;
const idField = option.idField || option.idKey || 'id';
const parentIdField = option.parentIdField || option.pidKey || 'parentId';
const childrenField = option.childrenField || option.childKey || 'children';
const parentIdIsNull =
typeof option.parentId === 'undefined' && typeof option.pid === 'undefined';
const parentId = parentIdIsNull ? [] : option.parentId ?? option.pid;
const addParentIds = option.addParentIds ?? option.addPIds;
const parentIdsField =
option.parentIdsField || option.parentsKey || 'parentIds';
const parentIds = option.parentIds;
if (parentIdIsNull) {
data.forEach((d) => {
let flag = true;
for (let i = 0; i < data.length; i++) {
if (d[parentIdField] == data[i][idField]) {
flag = false;
break;
}
}
if (flag) {
parentId.push(d[parentIdField]);
}
});
}
const result = [];
data.forEach((d) => {
if (d[idField] == d[parentIdField]) {
throw new Error(
[
'data error: {',
idField + ': ',
JSON.stringify(d[idField]),
parentIdField + ': ',
JSON.stringify(d[parentIdField]),
'}'
].join('')
);
}
const isArr = Array.isArray(parentId);
const isParent = isArr
? parentId.includes(d[parentIdField])
: d[parentIdField] == parentId;
if (isParent) {
const r = Object.assign({}, d);
const children = toTreeData({
data,
idField,
parentIdField,
childrenField,
parentId: d[idField],
addParentIds,
parentIdsField,
parentIds: (parentIds ?? []).concat([d[idField]])
});
if (children.length > 0) {
r[childrenField] = children;
}
if (addParentIds) {
r[parentIdsField] = parentIds ?? [];
}
result.push(r);
}
});
return result;
}
数组对象中过滤掉空数组和空字符串
let arr = [
{ location: 'a' },
{ location: [] },
{ location: 'b' },
{ location: '' }
];
console.log('过滤前:', arr);
console.log(
'过滤后:',
arr.filter((item) => Object.keys(item.location).length !== 0)
);
js获取数组维数【1,2,3,4维】
//获取数组维数。最长支持到四维数组判断。
// -1:非数组;0:空数组;1:一维数组;2:二维数组;3:三维数组;4:四维数组
getArrayDimension(arr) {
if (!Array.isArray(arr)) {
console.log(`参数不是数组`);
return -1;
} else if (arr.length == 0) {
console.log(`参数为空数组`);
return 0;
} else if (
Array.isArray(arr[0]) &&
Array.isArray(arr[0][0]) &&
Array.isArray(arr[0][0][0]) &&
!Array.isArray(arr[0][0][0][0])
) {
console.log(`参数是四维数组`);
return 4;
} else if (
Array.isArray(arr[0]) &&
Array.isArray(arr[0][0]) &&
!Array.isArray(arr[0][0][0])
) {
console.log(`参数是三维数组`);
return 3;
} else if (Array.isArray(arr[0]) && !Array.isArray(arr[0][0])) {
console.log(`参数是二维数组`);
return 2;
} else if (!Array.isArray(arr[0])) {
console.log(`参数是一维数组`);
return 1;
}
}
测试:
// 二维数组
let arr2 = [
[103, 30],
[104, 31],
[105, 32]
];
// 三维数组
let arr3 = [
[
[90, 20],
[100, 40]
],
[
[103, 30],
[104, 31],
[105, 32]
]
];
// 四维数组
let arr4 = [
[
[
[40, 30],
[100, 40]
]
],
[
[
[90, 20],
[100, 45]
],
[
[103, 30],
[104, 31],
[105, 32]
]
]
];
this.getArrayDimension(arr2);
this.getArrayDimension(arr3);
this.getArrayDimension(arr4);
获取数组最大值最小值
- 获取数组最大值:Math.max(...arr)
- 获取数组最小值:Math.min(...arr)
二维数组,获取最大最小经纬度
经纬度二维数组格式如:[[104,30],...,[105,33]]
// 根据经纬度二维数组获取最大最小经纬度。
// 经纬度二维数组格式如:[[104,30],...,[105,33]]
getMaxMinByLongitudeAndLatitudeArray(arr) {
let arr_longitude = []; //经度
let arr_latitude = []; //纬度
for (const item of arr) {
arr_longitude = [...arr_longitude, item[0]];
arr_latitude = [...arr_latitude, item[1]];
}
const region = {
longitude_max: Math.max(...arr_longitude),
longitude_min: Math.min(...arr_longitude),
latitude_max: Math.max(...arr_latitude),
latitude_min: Math.min(...arr_latitude)
};
return region;
},
使用:
let arr = [
[103.743896484375, 21.48374090716327],
[101.05224609374999, 20.550508894195637],
[103.60107421874999, 17.518344187852218]
];
console.log('原数组:', arr);
let region = this.getMaxMinByLongitudeAndLatitudeArray(arr);
console.log('获取二维数组最大值最小值:', region);
三维、四维数组,获取最大最小经纬度
getArrayDimension()和getMaxMinByLongitudeAndLatitudeArray()见上面的示例
test(arr) {
//获取数组维数
let arrDimension = this.getArrayDimension(arr);
if (arrDimension == 2) {
return this.getMaxMinByLongitudeAndLatitudeArray(arr);
}
if (arrDimension == 3) {
let newarr = [];
for (const item of arr) {
newarr = [...newarr, ...item];
}
return this.getMaxMinByLongitudeAndLatitudeArray(newarr);
}
if (arrDimension == 4) {
let newarr = [];
for (const item of arr) {
for (const data of item) {
newarr = [...newarr, ...data];
}
}
return this.getMaxMinByLongitudeAndLatitudeArray(newarr);
}
},
字符串数组转带引号字符串
- 传入:["a"] ,返回 'a'
- 传入:["a", "b", "c", "d"],返回 'a','b','c','d'
// 传入:["a"] ,返回 'a'
// 传入:["a", "b", "c", "d"],返回 'a','b','c','d'
function format_arr_to_str(arr = ["a", "b", "c", "d"]) {
if (arr.length == 1) {
return `'${arr[0]}'`;
}
if (arr.length > 1) {
let str = `'${arr[0]}'`;
for (let i = 1; i < arr.length; i++) {
str += `,'${arr[i]}'`;
}
return str;
}
}
数组中给缺失的字段添加默认值
在做图表可视化的时候,通常会有这样一种场景,就是字段缺失。此时我们需要给缺失的字段添加默认值
let allUsers = [
{ id: 3, name: "张三" },
{ id: 4, name: "李四" },
{ id: 5, name: "王五" },
{ id: 6, name: "赵六" },
];
let arr2 = [
{ id: 3, name: "张三", value: 33 },
{ id: 4, name: "李四", value: 44 },
{ id: 6, name: "赵六", value: 66 },
];
/**
* 希望构造出以下形式:
* [
{ id: 3, name: "张三", value: 33},
{ id: 4, name: "李四", value: 44},
{ id: 5, name: "王五", value: 0},
{ id: 6, name: "赵六", value: 66},
]
*/
function test(allUsers, arr2) {
let arr = allUsers.map((item) => {
return {
id: item.id,
name: item.name,
value: 0,
};
});
arr.forEach((item) => {
for (const d of arr2) {
if (d.name == item.name) {
item.value = d.value;
}
}
});
console.log("arr:", arr);
}
test(allUsers, arr2);
获取前7天的日期并输出为数组
如当前日期是'2023-02-10',则输出以下内容
['2023-02-04', '2023-02-05', '2023-02-06', '2023-02-07', '2023-02-08', '2023-02-09', '2023-02-10']
// 获取前7天的日期并输出为数组
/**
* 如当前日期是'2023-02-10',则输出以下内容
* ['2023-02-04', '2023-02-05', '2023-02-06', '2023-02-07', '2023-02-08', '2023-02-09', '2023-02-10']
*/
getDateArr(dayCount = 7) {
let arr = [];
for (let i = 0; i < dayCount; i++) {
let dd = new Date();
dd.setDate(dd.getDate() - i); //获取dayCount天前的日期
let year = dd.getFullYear();
let mon = dd.getMonth() + 1; //获取当前月份的日期
let day = dd.getDate();
let a =
year +
"-" +
(mon < 10 ? "0" + mon : mon) +
"-" +
(day < 10 ? "0" + day : day);
arr.push(a);
}
return arr.reverse();
}
根据数组对象中的某个属性进行排序
// 根据数组对象中的某个属性进行排序
const sortBy = (property, asc = true) => {
return function (value1, value2) {
let a = value1[property]
let b = value2[property]
return asc ? a - b : b - a
}
}
测试:
let newArray = [{
name: "aaa",
value: 2
},
{
name: "ddd",
value: 0
},
{
name: "bbb",
value: 1
},
{
name: "eee",
value: 4
},
{
name: "ccc",
value: 3
}];
console.log("升序:", newArray.sort(sortBy('value')))
console.log("降序:", newArray.sort(sortBy('value', false)))