简体   繁体   中英

toString inside js function returns undefined and 0 value

I have function I have written for a Codewars test:

Your task is to make a function that can take any non-negative integer as a argument and return it with it's digits in descending order. Descending order means that you take the highest digit and place the next highest digit immediately after it.

Here is my function:

function descendingOrder(n) {
  // convert number into string
  var toStr = n.toString();
  console.log("converted to string:");
  console.log(n);

  // split string at "decimal" point
  strArray = toStr.split(".");
  console.log("split string");
  console.log(strArray);

  // create new array from decimal numbers
  strArray.splice(0,1);
  console.log("Array after split: " + strArray);

  // split into array
  for (var i=0; i<strArray.length; i++) {
    var splitStrArray = strArray[i].split("");
  }

  console.log("new split str Array:");
  console.log(splitStrArray);

  // loop array and: 1) convert to number 2) push to new array of numbers
  var numArray = [];
  for (var j=0; j<splitStrArray.length; j++) {
    numArray.push(Number(splitStrArray[j]));
  }

  // sort in descending order
  numArray.sort(function(a,b){return b-a});
  console.log("new array of numbers:");
  console.log(numArray);
}

descendingOrder(1.45312798);

1st Problem: Finding the result for undefined I received the following error:

TypeError: Cannot read property 'length' of undefined at descendingOrder at Object.exports.runInThisContext

I know the undefined value comes from assigning the result of n.toString to a variable.

I tried the following:

var toStr = '';
toStr = n.toString();

But to no avail.


2nd Problem: There is an out put value of 0 which is being put through my function

I did certain MDN and other questions before posting this one. Any comments or criticism on my logic with regards to the Codewars challenge is more than welcome. Thanks in advance for the help.

Not an answer to the question, but I thought it could be a lot shorter. You said non-negative integer but then use 1.45312798 in your code, so I used your example value. Would not take much to make it work with just an integer (would be a lot shorter).

 var n = 1.45312798; function sortNumb(n) { var p = n.toString().split("."); var s = (p[1]) ? "."+ p[1].split("").sort().reverse().join("") : ""; console.log(p[0]+s); } sortNumb(n); 

Something like this ?

 function descendingOrder(n) { console.log(n); // convert number into string var toStr = n.toString(); // split string into array strArray = toStr.split(""); var t = strArray.indexOf('.') + 1; // get decimal digits var newStr = strArray.splice(t); // arrange values by descending order newStr = newStr.sort().reverse(); var sortedNo = strArray.splice(0, t).concat(newStr).join(''); // print the sorted value console.log(sortedNo); } descendingOrder(1.45312798); 

This function does all :

function result(n) {
    var digs=[];
    if (n.toString().indexOf('.')>-1) {
        var m=n.toString().slice(0,n.toString().indexOf('.'));
    } else {
        var m=n.toString();
    }
    for (var i=0;i<m.length;i++) {
        digs.push(parseInt(m[i]));
    }
    return parseInt(digs.sort().reverse().join(''));
}
console.log(result(16435.43)) // 65431
console.log(result(16433153)) // 65433311

two compact versions with some ES6

//a utility
var sortNumericDecending = (a,b) => b-a;

//simple version that works with positive ints
function descendingOrder(n){
    return +String(n).split("").sort(sortNumericDecending).join("");
}

//takes floats and orders the decimal places
function descendingOrder(n){
    var [int, decimals] = String(+n).split(".");
    return decimals? 
        +(int + "." + decimals.split("").sort(sortNumericDecending).join("")):
        n;
}

//or the same without Array destructuring
function descendingOrder(n){
    var parts = String(+n).split(".");
    return parts.length > 1? 
        +(parts[0] + "." + parts[1].split("").sort(sortNumericDecending).join("")):
        n;
}

Besides your question, it's not clear anymore wich one you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM