1. 首页
  2. IT资讯

JavaScript 1点1点1点

1 使用reduce收集数组对象中的指定字段, 或根据指定字段帅选数据

// Array.reduce() let arrayReduce = [ 	{ 		code: 12, 		name: '上海' 	}, { 		code: 15, 		name: '北京' 	}, { 		code: 100, 		name: '天津' 	}, { 		code: 50, 		name: '重启' 	}, { 		code: 30, 		name: '贵州' 	}, { 		code: 7, 		name: '黑龙江' 	} ]; let allCode = arrayReduce.reduce((total, current) => { 	return total.concat(current.code); }, []); console.log(allCode); // [12, 15, 100, 50, 30, 7] let bigAreaName = arrayReduce.reduce((total, current) => { 	return current.code >= 30 ? total.concat(current.name) : total; }, []); console.log(bigAreaName); // ["天津", "重启", "贵州"] 

Array.reduce() MDN 文档

2 拍平数组

// Array.flat() let multidimensionalArray = [ 	1, 2, 4, 	[4, 5], 	{ 		name: 'Y0n9' 	}, 	[ 		[6, 7, [8, [9]]] 	] ]; // 参数4 是深度层级, 层级未知时支持传入Infinity  console.log(multidimensionalArray.flat(Infinity)); // [1, 2, 4, 4, 5, {…}, 6, 7, 8, 9] console.log(multidimensionalArray.flat(4)); // [1, 2, 4, 4, 5, {…}, 6, 7, 8, 9] 

Array.flat() MDN 文档

3 获取url中的参数

// URLSearchParams let url = new URL('https://www.baidu.com/s?wd=mdn&rsv_spt=21&f=8&rsv_bp=41&&ie=utf-8&rqlang=&tn=baiduhome_pg&ch=chn&rsv_enter=79&rsv_dl=ib&inputT=3112'); console.log(); let params = new URLSearchParams(url.search); for (let p of params) {   console.log(p);   /* 	["wd", "mdn"] 	["rsv_spt", "21"] 	["f", "8"] 	["rsv_bp", "41"] 	["ie", "utf-8"] 	["rqlang", ""] 	["tn", "baiduhome_pg"] 	["ch", "chn"] 	["rsv_enter", "79"] 	["rsv_dl", "ib"] 	["inputT", "3112"]   */ } let ie = params.get('ie'); console.log(ie); // utf-8 // URLSearchParams实例有get set has keys等方法 (实验性api); 

URLSearchParams MDN 文档

4 有保留性的替换字符串内容

// String.replace(res, '$n') let discountInfo = '满#5#, 跨店#95#折'; let repalceReg = /([#])(d+)([#])/g; let renderHTML = discountInfo.replace(repalceReg, '<span>$2</span>'); console.log(renderHTML); // 满<span>5</span>, 跨店<span>95</span>折 

String.repalce() MDN 文档

原文始发于:JavaScript 1点1点1点

主题测试文章,只做测试使用。发布者:酒颂,转转请注明出处:http://www.cxybcw.com/24846.html

联系我们

13687733322

在线咨询:点击这里给我发消息

邮件:1877088071@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

QR code