Javascript 将javascript数组转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5289403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:29:50  来源:igfitidea点击:

Convert javascript array to string

javascriptjqueryarraysstringfrontend

提问by Neo

I'm trying to iterate over a "value" list and convert it into a string. Here is the code:

我正在尝试遍历“值”列表并将其转换为字符串。这是代码:

var blkstr = $.each(value, function(idx2,val2) {                    
     var str = idx2 + ":" + val2;
     alert(str);
     return str;
}).get().join(", ");    

alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?

alert() 函数工作正常并显示正确的值。但不知何故,jquery 的 .get() 函数没有获得正确的对象类型并失败。我究竟做错了什么?

回答by Shadow Wizard is Ear For You

If valueis associative array, such code will work fine:

如果value是关联数组,这样的代码可以正常工作:

var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {                    
  var str = idx2 + ":" + val2;
  blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

(output will appear in the dev console)

(输出将出现在开发控制台中)

As Felix mentioned, each()is just iterating the array, nothing more.

正如 Felix 所提到的,each()只是迭代数组,仅此而已。

回答by Spiderman

Converting From Array to String is So Easy !

从数组转换为字符串是如此简单!

var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""

That's it Now A is a string. :)

就是这样 现在 A 是一个字符串。:)

回答by Justin

You can use .toString()to join an array with a comma.

您可以使用.toString()逗号连接数组。

var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c

Or, set the separator with array.join('; '); // result: a; b; c.

或者,使用 设置分隔符array.join('; '); // result: a; b; c

回答by Nicholas

not sure if this is what you wanted but

不确定这是否是您想要的,但是

var arr = [A, B, C];
var arrString = arr.join(", ");

This results in the following output:

这导致以下输出:

A, B, C

甲、乙、丙

回答by VIJAY P

Four methods to convert an array to a string.

将数组转换为字符串的四种方法。

Coercing to a string

强制为字符串

var arr = ['a', 'b', 'c'] + [];  // "a,b,c"

var arr = ['a', 'b', 'c'] + '';  // "a,b,c"

Calling .toString()

打电话 .toString()

var arr = ['a', 'b', 'c'].toString();  // "a,b,c"

Explicitly joining using .join()

显式加入使用 .join()

var arr = ['a', 'b', 'c'].join();  // "a,b,c" (Defaults to ',' seperator)

var arr = ['a', 'b', 'c'].join(',');  // "a,b,c"

You can use other separators, for example, ', '

您可以使用其他分隔符,例如, ', '

var arr = ['a', 'b', 'c'].join(', ');  // "a, b, c"

Using JSON.stringify()

使用 JSON.stringify()

This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.

这更干净,因为它引用数组内的字符串并正确处理嵌套数组。

var arr = JSON.stringify(['a', 'b', 'c']);  // '["a","b","c"]'

回答by Felix Kling

jQuery.eachis just looping over the array, it doesn't do anything with the return value?. You are looking for jQuery.map(I also think that get()is unnecessary as you are not dealing with jQuery objects):

jQuery.each只是在数组上循环,它对返回值没有任何作用. 您正在寻找jQuery.map(我也认为这get()是不必要的,因为您没有处理 jQuery 对象):

var blkstr = $.map(value, function(val,index) {                    
     var str = index + ":" + val;
     return str;
}).join(", ");  

DEMO

演示



But why use jQuery at all in this case? maponly introduces an unnecessary function call per element.

但是为什么在这种情况下完全使用 jQuery?map只为每个元素引入不必要的函数调用。

var values = [];

for(var i = 0, l = value.length; i < l; i++) {
    values.push(i + ':' + value[i]);
}

// or if you actually have an object:

for(var id in value) {
    if(value.hasOwnProperty(id)) {
        values.push(id + ':' + value[id]);
    }
}

var blkstr = values.join(', ');


?: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.

?:它只使用返回值是否应该继续遍历元素。返回“假”值将停止循环。

回答by Deepu Reghunath

Use join()and the separator.

使用join()和分隔符。

Working example

工作示例

var arr = ['a', 'b', 'c', 1, 2, '3'];

// using toString method
var rslt = arr.toString(); 
console.log(rslt);

// using join method. With a separator '-'
rslt = arr.join('-');
console.log(rslt);

// using join method. without a separator 
rslt = arr.join('');
console.log(rslt);

回答by buitanan

this's my function, convert object or array to json

这是我的函数,将对象或数组转换为 json

function obj2json(_data){
    str = '{ ';
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += "'" + i + "':" + obj2arr(v) ;
        else if ($.type(v)== 'array')
            str += "'" + i + "':" + obj2arr(v) ;
        else{
            str +=  "'" + i + "':'" + v + "'";
        }
    });
    return str+= '}';
}

i just edit to v0.2 ^.^

我只是编辑到 v0.2 ^.^

 function obj2json(_data){
    str = (($.type(_data)== 'array')?'[ ': '{ ');
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += '"' + i + '":' + obj2json(v) ;
        else if ($.type(v)== 'array')
            str += '"' + i + '":' + obj2json(v) ;
        else{
            if($.type(_data)== 'array')
                str += '"' + v + '"';
            else
                str +=  '"' + i + '":"' + v + '"';
        }
    });
    return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}

回答by Santosh Linkha

var arr = new Array();

var blkstr = $.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);
    return arr;
}).join(', ');

console.log(blkstr);

OR

或者

var arr = new Array();

$.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);

});

console.log(arr.join(', '));

回答by Fydo

convert an array to a GET param string that can be appended to a url could be done as follows

可以按如下方式将数组转换为可以附加到 url 的 GET param 字符串

function encodeGet(array){
    return getParams = $.map(array , function(val,index) {                    
        var str = index + "=" + escape(val);
        return str;
   }).join("&");
}

call this function as

将此函数称为

var getStr = encodeGet({
    search:     $('input[name="search"]').val(),
    location:   $('input[name="location"]').val(),
    dod:        $('input[name="dod"]').val(),
    type:       $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;

which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.

哪个会将用户转发到/site/search?带有在给encodeGet 的数组中列出的get 参数的页面。