【问题标题】:String concatenation in javascript outputs bad resultjavascript中的字符串连接输出错误结果
【发布时间】:2015-11-15 12:40:21
【问题描述】:

我想创建随机用户名。 我使用文件中的列表名称和名字,并从每个文件中随机获取一个。

var nameList= fs.readFileSync("random-name/names.txt").toString().split("\n");
var name = nameList[Math.ceil(Math.random()*nameList.length)];

var firstnameList= fs.readFileSync("random-name/first-names.txt").toString().split("\n");
var firstname= firstnameList[Math.ceil(Math.random()*firstnameList.length)];

当我想连接它们时出现问题:

console.log( name);
console.log( firstname);
console.log( firstname+"-"+name);

输出:

Brant
Jesselyn
-Brantyn

如果我静态设置变量namefirstname显然没有问题。

【问题讨论】:

  • 也许名字的末尾有一个 CR 字符?尝试打印字符串长度...
  • 你想要Math.floor 而不是Math.ceil
  • 你也是对的,但这不是当前的问题!

标签: javascript string concatenation


【解决方案1】:

出现问题是因为我用“\n”分割文件内容,每个名字和名字的末尾仍然有“\r”。

【讨论】:

    【解决方案2】:

    正如您自己所指出的,从输入中删除 \r,或者拆分为 \r?\n

    其他说明:

    • 不要重复自己。
    • 您的“随机项”计算错误,您应该使用floor,而不是ceil

    怎么样:

    function getLines(filename) {
        return fs.readFileSync(filename).toString().split(/\r?\n/);
    }
    Array.prototype.getRandomItem = function () {
        return this[Math.floor(Math.random() * this.length)];
    };
    

    var nameList = getLines("random-name/names.txt");
    var name = nameList.getRandomItem();
    
    var firstnameList = getLines("random-name/first-names.txt");
    var firstname = firstnameList.getRandomItem();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多