Javascript字符串转换和数组排序

标签 javascript arrays string sorting

我正在尝试在 JavaScript 学习网站上发起挑战。

说明是:

It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?

Example: a = "56 65 74 100 99 68 86 180 90"ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99" When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string. All numbers in the list are positive numbers and the list can be empty.

我的尝试如下:

function orderWeight(strng) {

  console.log(strng);
  if (strng === "") {
    return strng;
  } else {
    var arr = strng.split(" ").sort();
    console.log(arr);
    var keys = [];

    for (var i = 0; i < arr.length; i++) {
      var weight = 0;
      var current = arr[i];
      //loop through the array adding the digits of each number
      for (var j = 0; j < arr[i].length; j++) {
        var sNum = parseInt(arr[i].charAt[j]);
        weight += sNum;
        console.log(weight);
      }
      keys.push({
        weight: weight,
        number: current
      });
      console.log(keys);
    }
  }
};

我的代码的输出是:

input string "103 123 4444 99 2000"
console.log(arr); = [ '103', '123', '2000', '4444', '99' ]
console.log(weight); = NaN

我意识到在我让这部分代码工作后我需要做更多的事情,但如果有人能指出我让这部分做我想做的事情的方向,我将非常感激。

最佳答案

调用 charAt 时,您使用方括号而不是圆括号。

更改此:

var sNum = parseInt(arr[i].charAt[j]);

至:

var sNum = parseInt(arr[i].charAt(j));

关于Javascript字符串转换和数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32082480/

相关文章:

javascript - 如何通过Sequelize连接多个数据库?

c# - 保存对已灭绝对象的引用的数组

javascript - 通过 javascript(包括 JSON 对象)访问在 Android 上使用 Java 创建的 JSON 数组

swift - Swift 中的 cos⁻¹ 按钮标题

c - 结构数组操作

javascript - Grails - 在 GSP 中渲染变量值时避免转换

javascript - 在 jQuery 中,使用 $.extend(),这是多余的吗?

javascript - 在后端代码中添加 JSON 中的额外字段

javascript - 来自 JQuery 数组的 Google 图表

ruby - 罗莎琳德:SUBS 在给定的案例中失败了