javascript数组作为字符串列表(保留引号) [英] javascript array as a list of strings (preserving quotes)

查看:1626
本文介绍了javascript数组作为字符串列表(保留引号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组.当我使用.toString()来输出它时,引号不会保留.这使得很难使用"in"来构建mysql查询.请考虑以下内容:

I've got an array of strings. When I use .toString() to output it the quotes are not preserved. This makes it hard to build the mysql query using an "in". Consider the following:

SELECT * FROM Table WHERE column IN ('item1','item2','item3','item4')

toString is returning: IN (item1,item2,item3,item4)

在这里我必须忽略一个简单的解决方法.

There must be a simple fix I am overlooking here.

推荐答案

由于引号实际上不是字符串值的一部分,所以不保留引号,它们只是在代码中指示字符串文字的必要条件.

The quotes aren't preserved because they're not actually part of the string value, they're just necessary to indicate string literals in your code.

因此,请勿使用toString().取而代之的是,一种方法如下:

So, don't use toString(). Instead, one way to do it is as follows:

var arr = ['item1','item2','item3','item4'];

var quotedAndCommaSeparated = "'" + arr.join("','") + "'";

// quotedAndCommaSeparated === "'item1','item2','item3','item4'"

Array.join()方法返回一个字符串这就是将所有数组元素串联成一个字符串,并在每个项目之间使用(可选)分隔符.因此,如果您指定一个包含引号和逗号的分隔符,则只需手动为第一项和最后一项分别添加起止号.

The Array.join() method returns a string that is all of the array elements concatenated into a single string with an (optional) separator between each item. So if you specify a separator that includes the quotation marks and commas you just have to manually append a starting and ending quote for the first and last item (respectively).

(然后告诉我您不是在使用客户端JavaScript来构成SQL.)

(And please tell me you're not using client-side JavaScript to form your SQL.)

要允许使用空数组,请为结果字符串包括默认值,否则(如missingno所指出),字符串将为"''":

to allow for an empty array, include a default value for the resulting string, otherwise (as pointed out by missingno) the string would be "''":

var newString = arr.length === 0 ? "" : "'" + arr.join("','") + "'";
// default for empty array here ---^^

(可能更适合让if (arr.length===0)采取其他措施,而不是运行SELECT语句.)

(Might be more appropriate to have an if (arr.length===0) to take some other action rather than running the SELECT statement.)

这篇关于javascript数组作为字符串列表(保留引号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆