返回最大值(ASCII)

时间:2019-03-30 04:52:53

标签: 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'

4 个答案:

答案 0 :(得分:3)

使用数组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'))

答案 1 :(得分:0)

要获取单个字符的ASCII值,请使用String.charCodeAt()

const string = "J";
//ASCII "J" is 74
console.log(string.charCodeAt(0));

答案 2 :(得分:0)

使用concatsort

function maxNum(array, str = -Infinity) {
  const charCode = (char) => isNaN(char) ? char.charCodeAt() : char;
  
  return [].concat(array, [str]).sort((a,b) => charCode(a) < charCode(b) ? 1 : -1)[0];
}

console.log(maxNum([1, 2, 3, 5], 10))
console.log(maxNum([1, 2, 3, 'a'], 10))
console.log(maxNum([1, 2, 3, 'a'], 'b'))

答案 3 :(得分:0)

function maxNum (array, str = -Infinity){
var max = 0;
var a = array.length;
var b = "";
for (counter=0;counter<a;counter++)
{
    let asc = array[counter];
    let asciicode = asc.toString().charCodeAt();
    if (asciicode > max)
    {
        max = asciicode ;
    }
    else if (max < b){
        max = b;
    }
}
return max > str ? max : str
}
console.log(String.fromCharCode( maxNum([1, 2, 3, 5, 'a', 'A', 's'], 10)));