javascript 数组作为字符串列表(保留引号)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8483179/
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
javascript array as a list of strings (preserving quotes)
提问by Anthony Webb
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:
我有一个字符串数组。当我使用 .toString() 输出它时,不会保留引号。这使得使用“in”构建 mysql 查询变得困难。考虑以下:
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.
我在这里忽略了一个简单的修复。
回答by nnnnnn
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.
引号不会被保留,因为它们实际上不是字符串值的一部分,它们只是在代码中指示字符串文字所必需的。
So, don't use toString()
. Instead, one way to do it is as follows:
所以,不要使用toString()
. 相反,一种方法如下:
var arr = ['item1','item2','item3','item4'];
var quotedAndCommaSeparated = "'" + arr.join("','") + "'";
// quotedAndCommaSeparated === "'item1','item2','item3','item4'"
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).
所述Array.join()方法返回一个字符串,它是所有连接成一个字符串与每个项目之间(可选的)分离器的阵列元件。因此,如果您指定一个包含引号和逗号的分隔符,您只需为第一项和最后一项(分别)手动附加开始和结束引号。
(And pleasetell me you're not using client-side JavaScript to form your SQL.)
(并且请告诉我您没有使用客户端 JavaScript 来形成您的 SQL。)
EDIT: to allow for an empty array, include a default value for the resulting string, otherwise (as pointed out by missingno) the string would be "''"
:
编辑:允许空数组,包括结果字符串的默认值,否则(如missingno指出的)字符串将是"''"
:
var newString = arr.length === 0 ? "" : "'" + arr.join("','") + "'";
// default for empty array here ---^^
(Might be more appropriate to have an if (arr.length===0)
to take some other action rather than running the SELECT statement.)
(可能更适合让 anif (arr.length===0)
执行一些其他操作而不是运行 SELECT 语句。)
回答by hugomg
The simple fix is adding the quotes yourself
简单的解决方法是自己添加引号
for(var i=0; i<items.length; i++){
items[i] = "'" + items[i] + "'";
}
var list_with_quotes = items.join(",");
Do note that I completely ignore SQL injection issues here.
请注意,我在这里完全忽略了 SQL 注入问题。
回答by Lukasz Wiktor
Use Array.map
to wrap each element with quotes:
用于Array.map
用引号包裹每个元素:
items.map(function(item) { return "'" + item + "'" }).join(',');
The code gets simpler with ES6 features - arrow functions and template strings (implemented in node.js 4.0 and higher):
ES6 特性让代码变得更简单——箭头函数和模板字符串(在 node.js 4.0 及更高版本中实现):
items.map(i => `'${i}'`).join(',');
You may also use whitelisting to prevent SQL injections:
您还可以使用白名单来防止 SQL 注入:
const validItems = new Set(['item1', 'item2', 'item3', 'item4']);
items
.filter(i => validItems.has(i))
.map(i => `'${i}'`)
.join(',')
回答by Chakphanu Komasathit
let keys = ['key1','key2']
let keyWithQoutes = keys.map((it) => {return `'${it}'`})
let sql = `SELECT .... FROM ... WHERE id IN (${keyWithQoutes})`
console.log(sql)
output: "SELECT .... FROM ... WHERE id IN ('key1','key2')"
输出:“SELECT .... FROM ... WHERE id IN ('key1','key2')”
回答by RobG
Store the quotes:
存储报价:
var names = ["'item1'","'item1'","'item3'"];
alert('IN (' + names[1] + ')'); // IN ('item1')