JavaScript采坑

https://github.com/Paris0-0/Practise-JavaScript/issues

1、str.match() 方法返回的是数组,要用[0]得到值,如果匹配不到,返回null,用[0]会报错

2、str.forEach((element, index) => {……} 处理json

处理的是一个数组,如果json是最外面使用大括号包围的,表示定义了对象,所以不能直接处理,而用大括号括起来则是数组,可以进行处理

3、hasOwnProperty,相当于一个for循环遍历每个成员,用于遍历空键值的JSON
例:
var body = $response.body;
var path = $request.path;
body=JSON.parse(body);

if (path.indexOf("list") > -1){
	body["data"]["list"].forEach( (element,index) =>{
			element.isFree = "true"
	})
}
else{
	body["data"]["radios"].forEach((element,index) =>{
		if (element.hasOwnProperty(["isFree"]))
			element.isFree = "true"
	})
	body["data"]["sounds"].forEach((element,index) =>{
		if (element.hasOwnProperty(["isFree"])){
			element.isFree = "true"
//			console.log(element.isFree)
		}
	})
}

body=JSON.stringify(body);
$done({body});

4、字符串转json(非json类型的string,JSON.parse会报错)
var test={"Accept-Encoding":"gzip, deflate",
"Cookie":"skey=Mks05krsB9; uin=o1172056834; wxopenid=; wxrefresh_token=; wxuin=; pgv_pvid=5602133394",
"Connection":"keep-alive",
"Accept":"*/*",
"Host":"monitor.music.qq.com",
"User-Agent":"QQMusic/66873 CFNetwork/1121.2.2 Darwin/19.2.0",
"Accept-Language":"zh-cn"}

//法1
var str = "'" + JSON.stringify(test) + "'"
test3=(new Function("return " + str))()
test2=JSON.parse(test3)
console.log(test2)
//法2 使用eval()
//testJson=eval(testJson);//错误的转换方式
testJson = eval("(" + testJson + ")");