Javascript字符串转换和数组排序 [英] Javascript string conversion and array sort

查看:134
本文介绍了Javascript字符串转换和数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting a challenge on a JavaScript learning website.

说明如下:


决定将权重归因于数字。
数字的重量从现在开始将是其数字的总和。例如99将
具有权重18,100将具有权重1因此在列表100中将为
在99美元之前来看。给定一个FFC成员权重在
正常顺序的字符串,你可以用这些
数字的权重给出这个字符串吗?

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?

示例:
a =56 65 74 100 99 68 86 180 90按数字重量排序变为:100 180 90 56 65 74 68 86 99当两个数字具有相同的
重量时,让我们将它们分类为字符串而不是数字:
100在180之前,因为它的权重(1)小于
180(9)和180之前的90因为,具有相同的权重(9),它是
之前的字符串。列表中的所有数字都是正数
数字,列表可以为空。

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

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

I realise I will need to do more after I get this portion of code working but if someone could just point me in the direction of getting this part to do what I want I would much appreciate it.

推荐答案

你正在使用调用 charAt 时括号而不是括号。

You are using brackets instead of parentheses when calling charAt.

更改此:

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

to:

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

这篇关于Javascript字符串转换和数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆