一、在數組中搜索特定的值
<!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>