2015-06-18 34 views
2

假設我有一串由空格分隔的數字,我想返回最高和最低數字。 JS如何使用函數來實現最佳效果?例如:用空格返回數字串中的最高和最低數字

highestAndLowest("1 2 3 4 5"); // return "5 1" 

我想這兩個數字都要返回一個字符串。最低的數字先是一個空格,然後是最高的數字。

這是我到目前爲止有:

function myFunction(str) { 
    var tst = str.split(" "); 
    return tst.max(); 
} 
+1

http://jsfiddle.net/marcusdei/u4bhdxyf/2/ – mdarmanin

回答

3

您可以使用Math.min和Math.max,並利用它們在數組中返回結果,請嘗試:

function highestAndLowest(numbers){ 
 
    numbers = numbers.split(" "); 
 
    return Math.max.apply(null, numbers) + " " + Math.min.apply(null, numbers) 
 
} 
 

 
document.write(highestAndLowest("1 2 3 4 5"))

2

下面是改進解決方案並促進全球使用的代碼:

/* Improve the prototype of Array. */ 
 

 
// Max function. 
 
Array.prototype.max = function() { 
 
    return Math.max.apply(null, this); 
 
}; 
 

 
// Min function. 
 
Array.prototype.min = function() { 
 
    return Math.min.apply(null, this); 
 
}; 
 

 
var stringNumbers = "1 2 3 4 5"; 
 

 
// Convert to array with the numbers. 
 
var arrayNumbers = stringNumbers.split(" "); 
 

 
// Show the highest and lowest numbers. 
 
alert("Highest number: " + arrayNumbers.max() + "\n Lowest number: " + arrayNumbers.min());

+1

感謝。給予好評! – mdarmanin

相關問題