function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = document.getElementById("demo"); x.innerHTML = Array.isArray(fruits); }
Array.forEach()
forEach()方法为每个数组元素调用一次函数。
1 2 3 4 5 6 7
var txt = ""; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction);
function myFunction(value){ txt = txt + value + "<br>"; }
Array.map()
这个例子给每个数组值乘以2:
1 2 3 4 5 6
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction);
function myFunction(value) { return value * 2; }
Array.filter()
此例用值大于18的元素创建一个新数组:
1 2 3 4 5
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; }
Array.reduce()
这个例子确定数组中所有数的总和:
1 2 3 4 5 6
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction);
function myFunction(total, value) { return total + value; }
Array.reduceRight()
这个例子同样是确定数组中所有数的总和:
1 2 3 4 5 6
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) { return total + value; }
Array.every()
这个例子检查是否所有值都超过18:
1 2 3 4 5 6
var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction);
function myFunction(value) { return value > 18; }
Array.some()
这个例子检查某些值是否超过18:
1 2 3 4 5 6
var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.some(myFunction);
function myFunction(value) { return value > 18; }
Array.indexOf()
检索数组中的某个元素值并返回其位置:
1 2
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple");