Home >Web Front-end >JS Tutorial >Example tutorial of code war

Example tutorial of code war

零下一度
零下一度Original
2017-06-23 09:35:331335browse

Today I will continue to do a question about arrays:

One difficulty here is that there are negative numbers in the numerical sorting. Sorting using sort will also report an error.

So, after several thoughts and tests, my answer is as follows:

function highAndLow(numbers){  var numArr=[],numArr1=[],numArr2=[];
  numbers.split(' ').map(function(n){      if(n>=0){
          numArr2.push(n);
      }else{
          numArr1.push(n);
      }
  });
  numArr1.sort((a,b)=>b-a);
  numArr2.sort((a,b)=>b-a);
  numArr = numArr2.concat(numArr1);
  numArr.splice(1,numArr.length-2);  return numArr.join(' ')
}

First divide the positive and negative numbers into two groups, then sort them separately, and finally merge the arrays , just take the first and last digits of the array.

The method is a bit stupid. Hahaha, I am that stupid bird.

Finally check out the code written by others:

The most practical one is

function highAndLow(numbers){
  numbers = numbers.split(' ').map(Number);  return Math.max.apply(0, numbers) + ' ' + Math.min.apply(0, numbers);
}

directly uses the max and min methods of Math (I Why didn't you think of it? Pig head, 555...)

There is another one that is closest to my original idea:

function highAndLow(numbers){  var arr = numbers.split(' ').sort(function(a, b) { return a - b });  return arr[arr.length -1] + ' ' + arr[0];
}

It's just that I wrote it as

function highAndLow(numbers){
  numbers.split(' ').sort((a, b)=> a - b });
  numbers.splice(1,numbers.length-2);  return numbers.join(' ');
}

Because the numbers were not converted into an array, an error occurred (low-level error)

The above is the detailed content of Example tutorial of code war. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use color in CSSNext article:How to use color in CSS