【问题标题】:.sort method not working, any hints why is that?.sort 方法不起作用,任何提示为什么会这样?
【发布时间】:2020-03-25 13:20:51
【问题描述】:
const sortYears = function (arr){
    arr.sort(function(a, b){return b - a})
    }



 const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]

 console.log(sortYears(years))

输出:未定义。我期待的输出:[ 2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922 ] 感谢一百万在这里的任何帮助

【问题讨论】:

  • 您的函数没有返回任何内容,但您正在记录函数的返回值。要么返回一些东西,要么做console.log(years)
  • const sortYears = (arr) => arr.sort( (a, b)=> b - a );

标签: javascript sorting methods


【解决方案1】:

你需要从函数中返回值

const sortYears = function (arr){
    return arr.sort(function(a, b){return b - a})
}

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
console.log(sortYears(years))

sort() 方法修改原始数组。在上面的 sn -p 中,years 数组也发生了变化。

如果不想修改原始数组,请确保先使用扩展语法克隆它。

const sortYears = function (arr){
    return [...arr].sort(function(a, b){return b - a})
}

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922];
const res= sortYears(years);
console.log(JSON.stringify(res));
console.log(JSON.stringify(years));

【讨论】:

  • 或者改为console.log(years)
【解决方案2】:

const sortYears = function (arr){
    arr.sort(function(a, b){return b - a})
      return arr;
    }



 const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]

 console.log(sortYears(years))
 

you did not return the sorted array back

【讨论】:

    【解决方案3】:

    实际上你并没有从sortYears() 函数返回任何东西。

    const sortYears = function (arr){
        return arr.sort(function(a, b){return b - a})
    }
    

    在这里,我使用箭头函数使用较短的语法。

    const sortYears = arr => arr.sort((a,b)=> b-a);
    
    const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
    console.log(sortYears(years))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多