You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeSignal中JavaScript的GET_NEXT操作测试失败,求代码问题排查

问题排查:GET_NEXT操作未返回预期值

在codesignal的JavaScript练习中,我需要实现一个支持ADD、REMOVE、GET_NEXT等操作的容器,其中GET_NEXT要求返回容器中严格大于给定值的最小整数,无符合值则返回空字符串。多数测试用例已通过,但最后一个测试用例中,最后一次执行GET_NEXT("5")时返回空字符串,而预期结果为"11"。

测试用例

> Input:
queries:
[["ADD","0"], 
 ["ADD","1"], 
 ["ADD","1"], 
 ["ADD","11"], 
 ["ADD","22"], 
 ["ADD","3"], 
 ["ADD","5"], 
 ["GET_NEXT","0"], 
 ["GET_NEXT","1"], 
 ["REMOVE","1"], 
 ["GET_NEXT","1"], 
 ["ADD","0"], 
 ["ADD","1"], 
 ["ADD","2"], 
 ["ADD","1"], 
 ["GET_NEXT","1"], 
 ["GET_NEXT","2"], 
 ["GET_NEXT","3"], 
 ["GET_NEXT","5"]]
Output:
["", "", "", "", "", "", "", "1", "3", "true", "3", "", "", "", "", "2", "3", "5", ""]
Expected Output:
["", "", "", "", "", "", "", "1", "3", "true", "3", "", "", "", "", "2", "3", "5", "11"]

我的代码

function solution(queries) {
const values = [];
const results = [];

queries.map(query =>{
    const [operation, value] = query;
    
    if(operation === "ADD"){
        values.push(value);
        results.push("")
    }
    
    if(operation === "EXISTS"){
        const exists = values.includes(value);
        results.push(exists.toString())
    }
   if(operation === "REMOVE"){
        const indexOfValue = values.indexOf(value);
        const exists = values.includes(value);
        
        if(exists){
        values.splice(indexOfValue, 1);
        }
        
        results.push(exists.toString())
    }
  if(operation === "GET_NEXT"){
    const filteredValues = values.filter(val => val > value);
    filteredValues.sort((a, b) => a - b);
    const nextValue = filteredValues[0] || "";
    results.push(nextValue);
    }
});

return results;
}

问题原因

问题出在字符串与数字的比较逻辑上:所有存入values数组的元素都是字符串类型,当执行val > value比较时,JavaScript会按字符串的ASCII码顺序进行比较,而非数值大小。例如"11"和"5"比较时,"1"的ASCII码小于"5",所以"11" > "5"会返回false,导致"11"被过滤掉,最终找不到符合条件的值,返回空字符串。

解决方案

有两种可行的修改方式:

方式1:存入时转换为数字类型

在ADD操作中,将输入的字符串值转换为数字后存入数组,同时在返回结果时转回字符串:

if(operation === "ADD"){
    values.push(Number(value)); // 转成数字存储
    results.push("")
}

// GET_NEXT部分修改返回逻辑
if(operation === "GET_NEXT"){
    const numValue = Number(value);
    const filteredValues = values.filter(val => val > numValue);
    filteredValues.sort((a, b) => a - b);
    const nextValue = filteredValues[0] !== undefined ? filteredValues[0].toString() : "";
    results.push(nextValue);
}

方式2:比较和排序时转换为数字

如果需要保持数组元素为字符串类型,在过滤和排序时显式转换为数字:

if(operation === "GET_NEXT"){
    const numValue = Number(value);
    const filteredValues = values.filter(val => Number(val) > numValue);
    filteredValues.sort((a, b) => Number(a) - Number(b));
    const nextValue = filteredValues[0] || "";
    results.push(nextValue);
}

两种方式都能解决字符串比较的问题,确保11作为数值大于5,会被正确筛选并返回。

内容的提问来源于stack exchange,提问作者Ioseb Khetsuriani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:17:42