javascript - 返回最大值 (ASCII)

标签 javascript loops

我有这个代码

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/

相关文章:

ios - 如何快速循环 UIBezierPath 中的点?

java - 循环程序直到0(退出)(java)

c++ - 如何在 C++ 中遍历句子中的单词?

node.js - Node : Sending UDP packet on timer,无限循环

python - 从 for 循环内部保存数据帧

javascript - 为什么 ember.run 调用在 ember.run.later 安排的工作完成之前完成?

javascript - 使用 JQuery 从具有 JSON 值的表中选择行

css 代码行上的 javascript 未知错误

javascript - 随机日期计算引导日期选择器,将天数添加到特定日期

javascript - 在屏幕调整大小时将 Div 居中