JavaScript 将数组打印为带括号和引号的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29956228/
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-10-28 11:23:32  来源:igfitidea点击:

JavaScript print array to string with brackets and quotes

javascript

提问by ngplayground

var fruits = ["Banana", "Orange", "Apple", "Mango"];

If I had the above array and wanted to output it to the user in the DOM as ["Banana", "Orange", "Apple", "Mango"]

如果我有上面的数组并想将它输出给 DOM 中的用户 ["Banana", "Orange", "Apple", "Mango"]

What would be the best way to do this?

什么是最好的方法来做到这一点?

I have tried fruits.toString();which outputs as Banana,Orange,Apple,Mango

我试过fruits.toString();哪些输出为Banana,Orange,Apple,Mango

回答by Yang Li

Use JSON.stringify

使用 JSON.stringify

JSON.stringify(fruits)

回答by yopefonic

in order to do that you'll need to iterate through the array and build the string from scratch.

为此,您需要遍历数组并从头开始构建字符串。

so something like this:

所以像这样:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

// first make sure that each fruit is between quotes
var fruitsResult = fruits.map(function(fruit) {
    return '"' + fruit + '"';
});

// join the fruits with the comma's in between
var result = fruitsResult.join(', ');

// add the final brackets around it
result = '[' + result + ']'

This is a basic solution that you can either add as a single function somewhere and pass the array to our you can extend the Array prototype with your own method so you can call fruits.toMyStringFunction(). It's up to you how you want to implement this.

这是一个基本的解决方案,您可以将其作为单个函数添加到某处并将数组传递给我们,您可以使用自己的方法扩展 Array 原型,以便调用fruits.toMyStringFunction()。您想如何实现这一点取决于您。

Note:that I'm using the Array.prototype.map()method that is supported in modern browsers but will cause some issues with IE8 and lower. This step can also be done using a for loop but this is more elegant.

注意:我正在使用现代浏览器支持的Array.prototype.map()方法,但会导致 IE8 及更低版本的一些问题。这一步也可以使用 for 循环来完成,但这更优雅。

回答by am2124429

If for some reason you don't want to use JSON, you could also use join.:

如果由于某种原因你不想使用 JSON,你也可以使用 join。:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var fruitsString = '["' + fruits.join('", "') + '"]';

Note: For mulitdimensional arrays see javascript - Convert array to string while preserving brackets.

注意:对于多维数组,请参阅javascript - 将数组转换为字符串,同时保留方括号