一、在数组中搜索特定的值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var friends = ["xushuai", "huxiang", "xutao", "zhuxiao", "biangou", "wangrui", "heizi"];
console.log(friends.length);
console.log(friends.indexOf("xutao"));
console.log(friends.lastIndexOf("huxiang"));
console.log(friends.indexOf("xu"));
//3个参数,数组元素、索引和数组自身
var mat = friends.findIndex(function (element) {
return (element == "biangou");
});
console.log(friends[mat]);
</script>
</body>
</html>
二、将两位数组扁平化
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var friendArray = [];
friendArray[0] = ["xushuai", "xianggou"];
friendArray[1] = ["xutao", "biangou"];
friendArray[2] = ["wangrui"];
friendArray[3] = ["heizi", "paoshen"];
//扁平化数组
var newArray1 = friendArray.concat.apply([], friendArray);
var newArray2 = friendArray[0].concat(friendArray[1], friendArray[2], friendArray[3]);
console.log(newArray1[2]);//xutao
console.log(newArray2[2]);//xutao
</script>
</body>
</html>
三、删除或替换数组元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var friends = ["shuai", "xiang", "tao", "xiao", "rui", "bin", "feng"];
//删除指定元素
var newArray1 = friends.splice(1, 2);
console.log(newArray1 + " " + friends);
var newArray2 = friends.splice(1, 2, "haha");
console.log(newArray2 + " " + friends);
</script>
</body>
</html>
四、提取一个数组的一部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var friends = ["shuai", "xiang", "tao", "xiao", "rui", "bin", "feng"];
var newArray = friends.slice(2, 5);
console.log(newArray);
</script>
</body>
</html>
五、对每个数组元素应用一个函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var friends = ["shuai", "xiang", "tao", "xiao", "rui", "bin", "feng"];
//element,index,array
function replaceValue() {
if (arguments[0] == "xiang")
arguments[2][arguments[1]] = "@@@";
}
//对数组的每一项应用一个函数
friends.forEach(replaceValue);
console.log(friends);
</script>
</body>
</html>
七、对数组中的每个元素执行一个函数并返回一个新数组
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var friends = ["shuai", "xiang", "tao", "xiao", "rui", "bin", "feng"];
var newArray = friends.map(function (element) {
return element + "*";
});
console.log(newArray);
</script>
</body>
</html>
foreach()方法和map()方法对每一个数组元素应用一个回调函数。前者是修改最初的数组,后者的结果是一个新的数组,而不是原来的数组。因此,前者不返回值,后者返回。
传递给map()方法的函数有3个参数:当前的数组元素可选的数组索引和数组(element,index,array),只有第一个参数是必需的。
八、创建一个过滤后的数组
<script>
过滤一个数组中的元素的值,并把结果赋给一个新的数组
var friends = ["shuai", "xiang", "tao", "xiao", "rui", "bin", "feng"];
var newArray = friends.filter(function (element) {
return (element == "xiang");
});
console.log(newArray);
</script>