【问题标题】:Why does array.prototype.slice() with no arguments change my output?为什么不带参数的 array.prototype.slice() 会改变我的输出?
【发布时间】:2020-07-12 23:33:23
【问题描述】:

我正在 leetcode 上做这个挑战。

为什么,这个答案被接受了?

我的代码:

/**
 * @param {number[]} nums
 * @return {string[]}
 */
var findRelativeRanks = function(nums) {
    const map = new Map();
    let result;
    nums
        .slice()
        .sort((a, b) => b - a)
        .forEach((num, i) => map.set(num, (i + 1).toString()));
    result = nums.map(num => {
        switch(map.get(num)) {
            case "1":
                return "Gold Medal";
            case "2":
                return "Silver Medal";
            case "3":
                return "Bronze Medal";
            default:
                return map.get(num);
        }
    })
    return result;
};

但如果我只是删除.slice(),一些测试用例会失败。为什么?

【问题讨论】:

标签: javascript


【解决方案1】:

Slice 返回数组的浅拷贝。

nums.slice().sort(/* ... */).forEach()

  1. 用切片复制数组
  2. 对数组进行排序
  3. 迭代排序后复制的数组。

但是,对“nums”的进一步访问将不会被排序,因为副本没有被保存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2018-12-01
    • 1970-01-01
    • 2021-08-02
    • 2016-02-18
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多