Array.toString()返回数组而不是字符串-为什么? Java脚本

时间:2018-07-12 15:09:41

标签: javascript arrays tostring

我一直在使用一个函数将不同的字符串转换为snake_case。当我尝试使用Array.toString()将最终数组转换为字符串时,该函数仍会返回一个数组。例如,尝试标识(标点)。为什么underlinedStringNew是数组而不是字符串?

最好的问候 贝尼

let punctuated = ',Hello, World???'

function identify(input) {
  let array = input.split("");
  let smallArray = [];
  let newestArray = [];

  for (let i = 0; i < array.length; i++) {
    smallArray[i] = array[i].toLowerCase();
  }

  for (let i = 0; i < array.length; i++) {
    if (array[i] == "." && array[i + 1] == ".") {
      return "WtfCase";
    }
  }

  let underlinedString = input.replace(/[^A-z]/g, "_");

  let smallUnderlinedArray = [];
  let capitalizedLetters = [];
  let underlinedArray = underlinedString.split("");
  console.log("Underlined Array: " + underlinedArray);

  for (let i = 0; i < underlinedArray.length; i++) {
    smallUnderlinedArray[i] = underlinedArray[i].toLowerCase();
  }

  for (let i = 1; i < underlinedArray.length; i++) {
    if (underlinedArray[i] !== smallUnderlinedArray[i]) {
      capitalizedLetters.push(i);
    };
  };

  for (let i = 0; i < capitalizedLetters.length; i++) {
    underlinedArray.splice(capitalizedLetters[i], 0, "_");
  }

  let i = 0;
  for (i; i < underlinedArray.length; i++) {
    if (underlinedArray[i] == "_" && underlinedArray[i + 1] == "_") {
      underlinedArray.splice(i, 1);
      i = i - 1;
    };
  };

  if (underlinedArray[underlinedArray.length - 1] == "_") {
    underlinedArray.splice(underlinedArray.length - 1, 1);
  }

  if (underlinedArray[0] == "_") {
    underlinedArray.splice(0, 1);
  }

  let underlinedStringNew = underlinedArray.toString();
  console.log("Should be a string: " + underlinedStringNew);

};

2 个答案:

答案 0 :(得分:3)

我认为您正在寻找的是不包含,的情况下连接数组的元素。默认情况下,join添加,。如果要删除它们,请使用空字符串''

// note that I simply a bit your code just to showcase the solution.
var a = ',Hello, World???'.replace(/[^A-z]/g, "_").split("").join('');
console.log("Should be a string: " + a);

输出:

Should be a string: _Hello__World___

如果您想了解有关join的更多信息,请检查MDN。一些例子:

var elements = ['Fire', 'Wind', 'Rain'];

console.log(elements.join());
// expected output: Fire,Wind,Rain

console.log(elements.join(''));
// expected output: FireWindRain

console.log(elements.join('-'));
// expected output: Fire-Wind-Rain

答案 1 :(得分:1)

您的代码应该没问题。例如,

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();

如果进行管理,您将看到类似Banana,Orange,Apple,Mango

的结果

但是如果您要替换逗号(,)并将其替换为空格

假设

var punctuated = "Banana,Orange,Apple,Mango"
punctuated.split(",").join(" ");

结果将为Banana Orange Apple Mango

要了解有关从字符串进行替换的更多信息,可以关注此link