我有一个数组,其中每个元素对应于一个字母数字字符串,让我们说:
userIds :Ab526,shvx23 23,23636dsd
我希望将它转换成这样的格式,这样我就可以将这个字符串列表传递给mySQL query的mySQL IN子句,如下所示:
从“(.)”中userIds所在的用户中选择*;
我尝试使用array.join()和许多其他方法,这些方法都是在某个地方提出的,但都是徒劳的。
var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids = userIds.join(',');
var query = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);
其结果是:
从userIds所在的用户中选择* ('Ab526,shvx23,23636dsd');
如果有人能提出一个解决方案,作为我如何能够实现我想要的,这将是非常有帮助的。
发布于 2017-04-02 08:04:00
您可以映射引文值并在稍后加入。
var userIds = ['Ab526', 'shvx23', '2363\'6dsd'],
result = userIds.map(function (a) { return "'" + a.replace("'", "''") + "'"; }).join();
console.log(result);
发布于 2017-04-02 08:20:24
您可以在数组上使用减缩:
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var clause = userIds.reduce(
function (cl , a, currIndex, arr)
{
return cl +
(currIndex == 0 ? "" : ",")
+"'"+ a + "'"+
(currIndex == arr.length-1 ? ")" : "") ; } , "(" );
console.log(clause );
发布于 2017-04-02 08:21:44
您可以使用以下代码:
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);
https://stackoverflow.com/questions/43166013
复制相似问题