简体   繁体   English

js函数中的toString返回undefined和0值

[英]toString inside js function returns undefined and 0 value

I have function I have written for a Codewars test: 我具有为Codewars测试编写的功能:

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 TypeError:无法读取Object.exports.runInThisContext处DescendingOrder的undefined属性“ length”

I know the undefined value comes from assigning the result of n.toString to a variable. 我知道未定义的值来自将n.toString的结果分配给变量。

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 第二个问题:通过我的函数输出的输出值为0

I did certain MDN and other questions before posting this one. 发布此问题之前,我做了一些MDN和其他问题。 Any comments or criticism on my logic with regards to the Codewars challenge is more than welcome. 我对有关Codewars挑战的逻辑的任何评论或批评都值得欢迎。 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. 您说的是非负整数,但是在代码中使用了1.45312798 ,所以我使用了示例值。 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 两个带有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. 除了您的问题,现在还不清楚您要的是哪一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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