简体   繁体   English

将数组(对象?)转换为JavaScript中的字符串

[英]Convert array(object?) to string in javascript

I am trying to convert this array into a string but it gives me the error: 我试图将此数组转换为字符串,但它给了我错误:

Object [object Array] has no method 'split'

I am converting to a string, so it shouldn't have that problem, I'm not sure why I am getting this error. 我正在转换为字符串,因此它应该不会出现该问题,我不确定为什么会收到此错误。

My code is: 我的代码是:

function preSubmit(){
    var optionTexts = [];
    $("section").each(function(){
        var h2 = $(this).find("h2").text();
        optionTexts.push(h2);
        $("ol li", this).each(function() { optionTexts.push($(this).text()); });
    });
    var optionTextString = optionTexts.toString();
    var splitText = optionTextString.split(",");
    console.log(splitText);
    return splitText;
}

The returned value of typeof splitText gives me [object Array], but I expect string . typeof splitText的返回值给了我[object Array],但是我希望是string

And it's true, array doesn't have any split method. 的确,数组没有任何拆分方法。 You're messing Join and Split methods, one belong to array, the other to string functions. 您搞砸了Join和Split方法,一个方法属于数组,另一个方法属于字符串函数。

What you want is: 您想要的是:

var splitText = optionTextString.join(",");

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

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