this.handleClick=(item)=>{
return ()=>{
console.log(item). //拿到了用户点击的那个
}
}
Arr.map(item=><div onClick={this.handleClick()}></div>)
function filesId(length?: number) {
const len = length || 32;
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
const maxPos = chars.length;
let pwd = '';
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
function generateUUID() {
function S4() {
const r = (1 + Math.random()) * 0x10000;
return (r || 0).toString(16).substring(1);
}
return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
};
const lowest = (categories, keyword) => {
return categories.reduce((pre, curv) => {
return pre[keyword] < curv[keyword] ? pre : curv;
}, {});
};
const obj = {
lowestPrice: lowest(goods.dishSkuVOS || [], 'sellPrice'),
lowestInventory: lowest(goods.dishSkuVOS || [], 'inventory')
}
/*
https://www.html.cn/archives/9318
JavaScript 中科学计数法相关的知识
对于极大或者极小的数,可以用科学计数法 e来表示的浮点数值来表示。
科学计数法允许字母e 或 E 的后面,跟着一个整数,表示这个数值的指数部分。
*/
function round(number, precision) {
return Math.round(`${+number}e${precision}`) / Math.pow(10, precision);
}
// 计算价格,保留两位小数,四舍五入,最小 0.01
function getPrice(discountType, originPrice, discountAmount) {
let price = 0;
// 折扣:原价5元,输入2,则打2折
switch (discountType) {
case 'DISCOUNT':
price = round((originPrice * discountAmount) / 10, 2);
break;
// 立减:原价5元,输入2,则返回3元
case 'REDUCE':
price = round(originPrice - discountAmount, 2);
break;
// 特价:原价5元,输入特价2元,则返回2元
case 'ONE_PRICE':
price = round(discountAmount, 2);
break;
default:
price = 0;
break;
}
return price;
}
console.log(getPrice('ONE_PRICE', 22, 10));
isNotCompleteNumber:判断不是数字的返回true,是数字返回false:
num.toString().indexOf('.') === num.toString().length - 1
判断’1.'小数点在最后一位则不是数字
JS中默认’1.'是数字,返回false。
const isNotCompleteNumber = (num) => {
return isNaN(num) || num === '' || num === null || num && num.toString().indexOf('.') === num.toString().length - 1;
};
abs = function (val) {
//金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
var str = (val / 100).toFixed(2) + "";
var intSum = str
.substring(0, str.indexOf("."))
.replace(/\B(?=(?:\d{3})+$)/g, ","); //取到整数部分
var dot = str.substring(str.length, str.indexOf(".")); //取到小数部分搜索
var ret = intSum + dot;
return ret;
};
abd = function (val) {
//金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
var str = (val / 100).toFixed(2) + "";
var intSum = str
.substring(0, str.indexOf("."))
.replace(/\B(?=(?:\d{3})+$)/g, ","); //取到整数部分
var dot = str.substring(str.length, str.indexOf(".")); //取到小数部分搜索
var ret = intSum + dot;
return ret;
};
// 元转分 - 解决精度问题 yuan:要转换的钱,单位元; digit:转换倍数
const regYuanToFen = (yuan, digit) => {
yuan = Number(yuan);
digit = Number(digit);
var m = 0,
s1 = yuan.toString(),
s2 = digit.toString();
try {
m += s1.split(".")[1].length;
} catch (e) {}
try {
m += s2.split(".")[1].length;
} catch (e) {}
return (
(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
Math.pow(10, m)
);
};
console.log(abs(32));
// console.log(regFenToYuan("12"));
console.log(regYuanToFen("100.00", 1));
const getRestDay = () => {
const endTime = new Date(applyEndTime);
const now = new Date();
const res = endTime.getTime() - now.getTime();
const day = res / (60 * 60 * 24 * 1000);
return Math.round(day);
};
// 提取一个包含键值的数组,其中。foo的值[1, 3, 5]...
const objArray = [ // 使用商品和对应门店
{
dishId: '200000000744450977',
dishType: 'SINGLE',
dishName: '菜品1',
unitName: '份',
dishImgId: 'http://cube.ar.elenet.me/1/b4/e829cb334b1b25f31153fb2717830JPEG.JPEG',
sellPrice: '4.44',
inventory: '10000',
multiSpecFlag: 'N',
state: 'ONLINE',
shopId: '2147566755', // 门店ID
shopName: '门店a',
dishSkuVOS: [
{
inventory: '10000',
sellPrice: '4.44',
skuId: '200000000779266977',
skuShopRelationAll: true,
skuName: '菜品1',
},
],
},
{
dishId: '200000000744450977',
dishType: 'SINGLE',
dishName: '菜品1',
unitName: '份',
dishImgId: 'http://cube.ar.elenet.me/1/b4/e829cb334b1b25f31153fb2717830JPEG.JPEG',
sellPrice: '4.44',
inventory: '10000',
multiSpecFlag: 'N',
state: 'ONLINE',
shopId: '2147566756', // 门店ID
shopName: '门店b',
dishSkuVOS: [
{
inventory: '10000',
sellPrice: '4.44',
skuId: '200000000779266977',
skuShopRelationAll: true,
skuName: '菜品1',
},
],
},
{
dishId: '200000000744450977',
dishType: 'SINGLE',
dishName: '菜品1',
unitName: '份',
dishImgId: 'http://cube.ar.elenet.me/1/b4/e829cb334b1b25f31153fb2717830JPEG.JPEG',
sellPrice: '4.44',
inventory: '10000',
multiSpecFlag: 'N',
state: 'ONLINE',
shopId: '3147566756', // 门店ID
shopName: '门店c',
dishSkuVOS: [
{
inventory: '10000',
sellPrice: '4.44',
skuId: '200000000779266977',
skuShopRelationAll: true,
skuName: '菜品1',
},
],
},
];
function getFields(input, field) {
const output = [];
for (let i = 0; i < input.length; ++i)
output.push(input[i][field]);
return output;
}
let result = getFields(objArray, "shopId"); // returns [ 1, 3, 5 ]
console.log(result);
var uuidArr = ["bbb", "vvv", "aaa", "fff", "fff"], flag = true;
var arr1 = [
{ "rolename": "aaa" },
{ "rolename": "bbb" },
{ "rolename": "ccc" },
{ "rolename": "ddd" }
];
var arr2 = [
{ "rolename": "eee" },
{ "rolename": "ccc" },
{ "rolename": "aaa" },
{ "rolename": "fff" }
];
// for (let i = 0; i < uuidArr.length; i++) {
// for (let j = i + 1; j < uuidArr.length; j++) {
// if (uuidArr[i] == uuidArr[j]) {
// flag = false;
// break;
// }
// }
// }
// if (!flag) {
// alert("有相同项!");
// } else {
// alert("都不相同")
// }
//数组求差
function getSubtract(unionArr, subsetArr) {
let new_tmp = new Array();
for (var i = 0; i < unionArr.length; i++) {
var flag = true;
for (var j = 0; j < subsetArr.length; j++) {
if (unionArr[i].rolename == subsetArr[j].rolename) {
flag = false;
}
}
if (flag) {
new_tmp.push(unionArr[i]);
}
}
return new_tmp;
}
var subtract = getSubtract(arr1, arr2);
console.log(subtract)
// ————————————————
var songs = [
{ name: "羽根", artist: "air" },
{ name: "羽根", artist: "air" },
{ name: "晴天", artist: "周杰伦" },
{ name: "晴天", artist: "周杰伦" },
{ artist: "周杰伦", name: "晴天" }
];
function unique(songs) {
let result = {};
let finalResult = [];
for (let i = 0; i < songs.length; i++) {
result[songs[i].name] = songs[i];
//因为songs[i].name不能重复,达到去重效果,且这里必须知晓"name"或是其他键名
}
//console.log(result);{"羽根":{name:"羽根",artist:"air"},"晴天":{name:"晴天",artist:"周杰伦"}}
//现在result内部都是不重复的对象了,只需要将其键值取出来转为数组即可
for (item in result) {
finalResult.push(result[item]);
}
//console.log(finalResult);[{name:"羽根",artist:"air"},{name:"晴天",artist:"周杰伦"}]
return finalResult;
}
console.log(unique(songs));
let arr1 = [{ id: 1, name: '网' }, { id: 2, name: '二位' }]
let arr2 = [{ id: 1, name: '问问' }, { id: 2, name: '多少1' }, { id: 44, name: '多少2' }, { id: 45, name: '多少3' },]
let add = arr2.filter(item => arr1.some(ele => ele.id === item.id))
console.log(add)
对象数组中的最大值
var array = [
{
"id": 52354541,
"name": "比率",
"value": "55"
},
{
"id": 43563123,
"name": "比率",
"value": "88"
},
{
"id": 32525763,
"name": "比率",
"value": "76"
}];
array.reduce(function (pre, curv) {
return pre.value < curv.value ? curv : pre;
}).id
//查看商品是否选择:返回some进行检测id是否已选择
infos.some(g => g?.sId === catogary.sId) && skus.some(d => d?.bId === bId);
//filter&some两个数组数据类型过滤
arr1.filter(a1=>arr2.some(a2.id===a1.id))
// 只能判断元素为简单数组类型;判断b是否包含在a中
var a = [1, 2, 7, 6];
var b = [6, 7, 2];
function isContained(aa, bb) {
if (!(aa instanceof Array) || !(bb instanceof Array) || ((aa.length < bb.length))) {
return false;
}
var aaStr = aa.toString();
for (var i = 0; i < bb.length; i++) {
if (aaStr.indexOf(bb[i]) < 0) return false;
}
return true;
}
var c = isContained(a, b);
console.log(c);
var a = [1, 2, 3, 4, 5]
var b = [2, 4, 6, 8, 10]
//交集a和b的交集
var c = a.filter(function (v) { return b.indexOf(v) > -1 })
console.log(c);
function equar(a, b) {
// 判断数组的长度
if (a.length !== b.length) {
return false
} else {
// 循环遍历数组的值进行比较
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false
}
}
return true;
}
}
console.log(equar([222, 333], [222, 333]))
var a = [{ name: 'zhangsan', age: '11' }, { name: 'wangwu', age: '12' }]
var b = [{ name: 'zhangsan', age: '11' }, { name: 'wang', age: '22' }]
// var newa = a.join(',')[Object Object]
// var newb = b.toString() [Object Object]
console.log(newa, newb)
console.log(newa.includes(newb))
let data = [
{
"categoryId": "91000033",
"children": [
{
"categoryId": "91612215",
"children": [
{
"categoryId": "99672434",
"children": [
{
"categoryId": "94574713",
"children": [
{
"categoryId": "1895621",
"children": [],
"categoryName": "肯德基宅急送(荡口古镇店)",
"storeCount": 1,
"type": "STORE",
"class": "com.alsc.pos.organization.client.model.dto.storebycity.StoreGroupNodeDTO",
"extInfo": {
"tbStoreId": "236656440",
"tbSellerId": "2201121248912",
"outMerchantAccount": "91000033",
"hasMergeToTb": "true",
"parentId": "94574713"
}
}
],
"categoryName": "新店",
"storeCount": 1,
"type": "CHAIN",
"class": "com.alsc.pos.organization.client.model.dto.storebycity.StoreGroupNodeDTO",
"extInfo": {
"tbStoreId": "null",
"hasMergeToTb": "null",
"parentId": "99672434"
}
}
],
"categoryName": "无锡肯德基有限公司",
"storeCount": 1,
"type": "CHAIN",
"class": "com.alsc.pos.organization.client.model.dto.storebycity.StoreGroupNodeDTO",
"extInfo": {
"tbStoreId": "null",
"hasMergeToTb": "null",
"parentId": "91612215"
}
}
],
"categoryName": "肯德基宅急送全国",
"storeCount": 1,
"type": "CHAIN",
"class": "com.alsc.pos.organization.client.model.dto.storebycity.StoreGroupNodeDTO",
"extInfo": {
"tbStoreId": "null",
"hasMergeToTb": "null",
"parentId": "91000033"
}
}
],
"categoryName": "肯德基宅急送",
"storeCount": 1,
"type": "CHAIN",
"class": "com.alsc.pos.organization.client.model.dto.storebycity.StoreGroupNodeDTO",
"extInfo": {
"tbStoreId": "null",
"hasMergeToTb": "null",
"parentId": "0"
}
}
]
// function f(arr, selectedKey) {
// debugger;
// return arr.filter(item => item.categoryId !== selectedKey).map(item => {
// item = Object.assign({}, item)
// if (item.children) {
// item.children = f(item.children, selectedKey)
// }
// return item
// })
// }
function filterTree(tree = [], map = [], arr = []) {
if (!tree.length) return []
for (let item of tree) {
if (!map.includes(item.id)) continue
let node = { ...item, children: [] }
arr.push(node)
if (item.children && item.children.length) filterTree(item.children, map, node.children)
}
return arr
}
// console.log(f(data, '1895621'))
console.log(filterTree(data, ['1895622']))
//先对数据进行扁平化再递归
/**
* @param {Array} treeArr 树型数组
*/
const treeToFloatTypeFn = (treeArr = [], key) => {
let newTree = []; // 生成一个新的平型
(function treeToFloatType(chArr) {
chArr.forEach(ele => { // 遍历树型
let newObj = {}
const keys = Object.keys(ele) // 获取每个树形对象中的key []
keys.forEach(el => { // 遍历key
if (ele.hasOwnProperty(el)) { // 判断是否是继承属性
if (ele[el] instanceof Array && ele[el] !== null) {
// 对象且非空 递归
treeToFloatType(ele[el])
} else {
// 非对象
newObj[el] = ele[el]
}
}
})
newTree.unshift(newObj)
});
})(treeArr)
return newTree
}
console.log(treeToFloatTypeFn(storeArr.data.data.children))
const arys = [{ a: 6 }, { a: 1 }, { a: 5 }, { a: 2 }];
let result = arys.filter(ary => ary.a !== 1).map(element => element.a);
console.log(result.sort().join(''));
const arr = Array(100);
const newArr = arr.fill(1);
async function test(){
await setTimeout(()=>{
console.log(1);
},0);
console.log(2);
}
test()//输出什么