js 解构赋值 从函数中返回多个值
例如:
//快速从返回的数组中取数
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
let[a,b,c] 就相当于 let arr 拿到其中的值也就是arr[0] arr[1] arr[2]
参考
使用数组
html>
<head>
<title>JS函数返回多个值--oec2003</title>
</head>
<body>
<input type="button" onclick="getNames()" value="test" />
<script type="text/javascript">
function getData()
{
var names=new Array("oec2003","oec2004");
return names;
}
function getNames()
{
var names=getData();
alert(getData()[0]); //返回oec2003
}
</script>
</body>
</html>
将数据封装到Json
<html>
<head>
<title>JS函数返回多个值--oec2003</title>
</head>
<body>
<input type="button" onclick="getInfo()" value="test"/>
<script type="text/javascript">
function getData()
{
var info={"name":"oec2003","age":"25"};
return info;
}
function getInfo()
{
var info=getData();
var name=info["name"];
var age=info["age"];
alert("姓名:"+name+" 年龄:"+age);
}
</script>
</body>
</html>
最后一种 也就是解构赋值的应用 比较简单
<html>
<head>
<title>JS函数返回多个值--oec2003</title>
</head>
<body>
<input type="button" onclick="getInfo()" value="test"/>
<script type="text/javascript">
function getData()
{
return ["oec2003", 25]
}
function getInfo()
{
var info = getData();
alert("姓名:" + info[0] + "年龄:" + info[1]);
}
</script>
</body>
</html>
扩展一下解构赋值的应用场景(参考阮一峰ES6教程):
//快速从返回的数组中取数
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
//快速从JSON中提取数据
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data} = jsonData;
//遍历map
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
//获取键
for (let [key] of map) {
// ...
}
//获取键值
for (let [,value] of map) {
// ...
}

浙公网安备 33010602011771号