简体   繁体   English

使用util.format,在数组中的每个字符串周围用双引号引起来

[英]Using util.format, double quotes around each string in an array

At the moment .. 在这一刻 ..

var util = require("util");

var carsInput = 'seat,ford';
var cars = carsInput.split(',');

var queryString = util.format('Cars: [%s]', cars);
console.log(queryString); // Cars: [seat,ford]

This is the aim: 目的是:

Cars: ["seat","ford"]

Is there a way to do this with util.format or do i need to loop and add the quotes to each element? 有没有办法用util.format做到这一点,或者我需要循环并将引号添加到每个元素吗?

It's actually as simple as: 实际上很简单:

var util = require('util');

var carsInput = 'seat,ford';
var cars = carsInput.split(',');

var queryString = util.format('Cars: %j', cars);
console.log(queryString); // Cars: ["seat","ford"]

Where %j is for JSON %j用于JSON

Read more on the docs 文档上阅读更多内容

Here is a way to not loop, at least not explicitly. 这是一种至少不会显式地不循环的方法。 It does not strictly answer your questions, since I do not have access to utils.format. 由于我无权访问utils.format,因此它不能严格回答您的问题。 Before you make your queryString say: 在使您的queryString之前,请说:

cars = cars.map(function(s){ return '"'+s+'"';});

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

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