从提示对字符串进行排序不起作用,但在硬编码时有效



当我通过提示给出值时,我的代码不起作用,但正在使用硬编码输入。

有人可以帮我理解为什么会这样吗?

var str=prompt("Enter String :: ");
alert(selectionSort(str));
function selectionSort(items){
    var len = items.length,
        min;
    for (i=0; i < len; i++){
        min = i;
        //check the rest of the array to see if anything is smaller
        for (j=i+1; j < len; j++){
            if (items[j] < items[min]){
                min = j;
            }
        }
        if (i != min){
            swap(items, i, min);
        }
    }
    return items;
}

这是我的交换功能:

function swap(items, firstIndex, secondIndex){
    var temp = items[firstIndex];
    items[firstIndex] = items[secondIndex];
    items[secondIndex] = temp;
}

如果您只想对字符进行排序,则可以使用:

var str = "farhan";
var sorted = str.split("").sort().join("");
console.log(sorted); // "aafhnr"

.split("")将字符串转换为数组。 .sort对数组进行排序(默认为升序),.join("")数组变回字符串。

出于教育目的,编写自己的排序例程可能很有用,但除此之外,请尽可能多地使用内置函数。

最新更新