find()方法返回数组中符合的第一个值,效果和swith类似,但是简单很多,
用法:
array.find(function(currentValue, index, arr),thisValue)
参数:
currentValue 必需。当前元素
index 可选。当前元素的索引值
arr 可选。当前元素所属的数组对象
thisValue 可选。 传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
方法返回值:返回符合测试条件的第一个数组元素值,如果没有符合条件的则返回 undefined。
EG:
var ages = [4, 12, 16, 20];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAdult);
}