我有这个代码
function maxNum (array, str = -Infinity){
var max = 0;
var a = array.length;
var b = "";
for (counter=0;counter<a;counter++)
{
if (array[counter] > max)
{
max = array[counter];
}
else if (max < b){
max = b;
}
}
return max > str ? max : str
}
console.log(maxNum([1, 2, 3, 5], 10));// output will be 10
它接收一个数组和一个值并返回最大的数字。(仅限数字)
如果给定一个字符,使用该字符的 ASCII 值并返回结果,如何使其工作
如何在代码中实现 String.charCodeAt():
?
我希望 ([1, 2, 3, 'a'], 10)
的输出为 'a'
和
我希望 ([1,2,3,4,'a','b'],'a')
的输出为 'b'
最佳答案
使用数组reduce()
和 charCodeAt()
function maxNum(array, str = -Infinity) {
return array.reduce((max, item) => {
let itemc = isNaN(item) ? item.charCodeAt() : item;
let maxc = isNaN(max) ? max.charCodeAt() : max;
return max = (itemc > maxc) ? item : max;
}, str)
}
console.log(maxNum([1, 2, 3, 5], 10))
console.log(maxNum([1, 2, 3, 'a'], 10))
console.log(maxNum([1, 2, 3, 'a','c'], 'b'))
console.log(maxNum([1, 2, 3, 'a'], 'b'))
使用charCodeAt()
的方法
function maxNum(array, str = -Infinity) {
var max = str;
var a = array.length;
for (counter = 0; counter < a; counter++) {
let itemc = isNaN(array[counter]) ? array[counter].charCodeAt() : array[counter];
let maxc = isNaN(max) ? max.charCodeAt() : max;
if (itemc > maxc) {
max = array[counter];
}
}
return max;
}
console.log(maxNum([1, 2, 3, 5], 10))
console.log(maxNum([1, 2, 3, 'a'], 10))
console.log(maxNum([1, 2, 3, 'a','c'], 'b'))
console.log(maxNum([1, 2, 3, 'a'], 'b'))
关于javascript - 返回最大值 (ASCII),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428288/