简体   繁体   English

数组到字符串的转换不起作用

[英]Array to string conversion not working

I am trying to print out this code in a string. 我正在尝试以字符串形式打印此代码。

var x = [[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]];`
console.log(x.toString());

This is what shows up. 这就是所显示的。

字符串数组

When I print out the regular string, like so- 当我打印出常规字符串时,就像这样-

console.log(x);

This is what shows up- 这是显示出来的-

数组

Is there any way I can print out a string with the square brackets? 有什么办法可以打印出带有方括号的字符串? I want the result to be something like "[[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]]" . 我希望结果是类似"[[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]]"

I need to add this value to a eval function, which is why I need to add the entire array (as a string with the brackets) to the function. 我需要将此值添加到一个eval函数,这就是为什么我需要将整个数组(带有括号的字符串)添加到该函数的原因。

Is there any way this can be possible (preferably without additional libraries)? 有什么办法可以做到(最好没有额外的库)?

Use JSON.stringify to convert the Array to a JSON Array. 使用JSON.stringify将数组转换为JSON数组。

var x = [[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]];
console.log(JSON.stringify(x));
// [[1,2,3,4.5,6],[7,8.5,9.5,10]]

You can use Array#map with string concatenation. 您可以将Array#map与字符串连接一起使用。

'[' + x.map(e => '[' + e + ']') + ']'

 var x = [ [1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10] ]; var string = '[' + x.map(e => '[' + e + ']') + ']'; console.log(string); document.body.innerHTML = string; 

If the elements of the main array are not always array , Array.isArray can be used with ternary operator . 如果主数组的元素不总是数组 ,则Array.isArray可以与三元运算符一起使用。

'[' + x.map(e => Array.isArray(e) ? '[' + e + ']' : e) + ']'

 var x = [ [1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10], 'name', 10 ]; var string = '[' + x.map(e => Array.isArray(e) ? '[' + e + ']' : e) + ']'; console.log(string); document.body.innerHTML = string; 

You can use JSON.stringify() to serialize x into a string. 您可以使用JSON.stringify()将x序列化为字符串。

console.log(JSON.stringify(x)) will return what you're looking for. console.log(JSON.stringify(x))将返回您要查找的内容。

 console.log(JSON.stringify(x))
 [[1,2,3,4.5,6],[7,8.5,9.5,10]]

The best way is to use the json.stringify() method.The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified. 最好的方法是使用json.stringify()方法。JSON.stringify()方法将JavaScript值转换为JSON字符串,如果指定了replacer函数,则可以选择替换值,如果替换器,则可以仅包括指定的属性。指定了数组。 MAy the below url help you where you can get complete reference. 可能下面的网址可以帮助您获得完整的参考。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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

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