<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>提取weapon数组的粗略方法</title>
<script src="../unitl/test.js"></script>
<style>
#results li.pass {color:green;}
#results li.fail {color:red;}
</style>
</head>
<body>
<ul id="results"></ul>
</body>
<script>
const ninjas = [
{name:"Yagyu",weapon:"shuriken"},
{name:"Yoshi",weapon:"katana"},
{name:"Kuma",weapon:"wakizashi"}
];
const weapons = [];
ninjas.forEach(ninja =>{
weapons.push(ninja.weapon);
});
assert(weapons[0] === "shuriken"
&& weapons[1] === "katana"
&& weapons[2] === "wakizashi"
&& weapons.length === 3,"The new Array contains all weapons"
);
</script>
</html>
首先创建一个空数组,使用forEach方法遍历ninjas数组。然后,将每个ninja对象的weapon属性添加到weapons数组中。可以想象,基于已有数组的元素创建数组是非常常见的,
因此它具有一个特殊的名称:映射数组。主要思想是将数组中的每个元素属性映射到新数组的元素上。javascript的map函数可以实现便捷操作。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>映射数组</title>
<script src="../unitl/test.js"></script>
<style>
#results li.pass {color:green;}
#results li.fail {color:red;}
</style>
</head>
<body>
<ul id="results"></ul>
</body>
<script>
const ninjas = [
{name:"Yagyu",weapon:"shuriken"},
{name:"Yoshi",weapon:"katana"},
{name:"Kuma",weapon:"wakizashi"}
];
const weapons = ninjas.map(ninja=>ninja.weapon);
assert(weapons[0] === "shuriken"
&& weapons[1] === "katana"
&& weapons[2] === "wakizashi"
&& weapons.length ===3, "The new Array contains all weapons!"
);
</script>
</html>
本例子中引入的js: test.js
内置的map方法创建了一个全新的数组,然后遍历输入的数组。对输入数组的每个元素,在新建的数组上,都会基于回掉函数的执行结果创建一个对应的元素。