如何在单引号中包装字符串组

时间:2016-09-15 22:08:43

标签: javascript jquery

我需要将数组的元素导出到字符串,但保留元素周围的单引号。正如您所看到的,将它们导出到ContentHolder.Source = new Uri("/XAML/Repository/Page1.xaml", UriKind.Relative); ResourceDictionary RD = new ResourceDictionary() { Source = new Uri("/NS01;component/XAML/Resources/Page1.xaml", UriKind.RelativeOrAbsolute) }; Application.Current.Resources.MergedDictionaries.Add(RD); Application.Current.Resources.MergedDictionaries.Remove(RD); foreach (var R in MWindow.Resources) { MessageBox.Show(R.ToString()); } 方法输出toString()但我需要像Banana, Orange, Apple, Mango一样。

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

console.log(map);

你能告诉我怎么做吗?

5 个答案:

答案 0 :(得分:3)

ES6

var fruits = ["Banana", "Orange", "Apple", "Mango"];
// creates a new array containing: ["'Banana'", "'Orange'", "'Apple'", "'Mango'"]
var exportedFruits = fruits.map(fruit => "'" + fruit + "'");
console.log(exportedFruits.toString())

ES5

var fruits = ["Banana", "Orange", "Apple", "Mango"];
// creates a new array containing: ["'Banana'", "'Orange'", "'Apple'", "'Mango'"]
var exportedFruits = fruits.map(function(fruit){
  return "'" + fruit + "'";
});
console.log(exportedFruits.toString())

答案 1 :(得分:1)

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var result = "'" + fruits.join("','") + "'";

答案 2 :(得分:0)

由于您使用的是jQuery,因此您可以使用jQuery的map

JavaScript ES6 / ES2015也有一个非常相似的Array.protytype.map

var arr = ['a', 'b', 'c'];

var res = $.map(arr, (function(val) {
  return "'" + val + "'";
  }));

console.log(res.join(","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

答案 3 :(得分:0)

这是一种方式。

&#13;
&#13;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var map = fruits.map(myFun).toString();

console.log(map);
function myFun(val,i,array){
    return "'"+val+"'";
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

我暂停了Array.map解决方案。一个地图做一个连接操作当然是有效的,但是有点沉重。我们认为我们在小型设备上处于系统纳米时间,但在处理时间至关重要的某些环境中它可能很重要。将大型数据集转换为逗号分隔的字符串,例如使用CSV导出是一种常见情况。良好的老式联手很难被击败。

//基于字符串数组编辑新的时间:

ES6 Array.map:18.2150 ms

ES5 Array.map:21.7800 ms

加入:3.5750毫秒

&#13;
&#13;
var map, start, end, fruits;


fruits = [];
for(var i = 0; i < 50000; i++){
 fruits.push(i.toString());
}

start = performance.now();
var exportedFruits = fruits.map(fruit => "'" + fruit + "'");
exportedFruits = exportedFruits.toString();
end = performance.now();
console.log((end - start).toFixed(4)+" ms");

start = performance.now();
var exportedFruits = fruits.map(function(fruit){
  return "'" + fruit + "'";
});
exportedFruits = exportedFruits.toString();
end = performance.now();
console.log((end - start).toFixed(4)+" ms");


start = performance.now();
map = "'" + fruits.join("','") +"'";
end = performance.now();
console.log((end - start).toFixed(4)+" ms");
   
&#13;
&#13;
&#13;

编辑:我忘了测量前两个的toString操作。