<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>找到合適的值</title>
<script>
window.onload = function (){
var arr = [ '100px', 'abc'-6, [], -98765, 34, -2, 0, '300', , function(){alert(1);}, null, document, [], true, '200px'-30,'23.45元', 5, Number('abc'), function(){ alert(3); }, 'xyz'-90 ];
/*
1、找到arr裡所有的數字:-98765, 34, -2, 0, 5
2、找到可以轉成數字的:'100px', -98765, 34, -2, 0, '300', '23.45元', 5
3、把轉成數字以後,最大值判斷出來:300
4、把 NaN 所在的位置找出來:1 14 17 19
*/
var num = '';
for (var i = 0; i < arr.length; i++) {
if(parseInt(arr[i])==arr[i]){
document.write(arr[i]+' ');
}
}
</script>
</head>
<body>
</body>
</html>
typeof判斷類型,然後parseFloat轉換,判斷結構是否NaN
<script>
var arr = ['100px', 'abc' -6, [], -98765, 34, -2, 0, '300', function () { alert(1); }, null, document, [], true, '200px' - 30, '23.45元', 5, Number('abc'), function () { alert(3); }, 'xyz' - 90];
var arrNum = [], arrCanParse = [],arrCanParseNum=[], max, arrNaNIndex=[],r;
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] == 'number' && !isNaN(arr[i])) arrNum.push(arr[i]);
else {
r = parseFloat(arr[i]);
if (isNaN(r)) arrNaNIndex.push(i);
else { arrCanParse.push(arr[i]);arrCanParseNum.push(r)}
}
}
console.log(arrNum)
console.log(arrCanParse)
console.log(arrNum.concat(arrCanParseNum).sort(function (a, b) { return b - a })[0]);
console.log(arrNaNIndex)
</script>