Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用下划线将数组或对象推入一个数组?_Javascript_Underscore.js - Fatal编程技术网

Javascript 如何使用下划线将数组或对象推入一个数组?

Javascript 如何使用下划线将数组或对象推入一个数组?,javascript,underscore.js,Javascript,Underscore.js,我基本上在mongo中使用$all操作符,我得到的输入可能是数组或单个元素,如下所示。那么,如何使用下划线将所有元素放在一个数组中,然后 userId = 'a'; userIds = ['a', 'b', 'c']; otherId = ['a'] or 'a'; searchArray = [userId, userIds, otherId] db.collections.find({userIds: {$all: searchArray}}) 只要是数组,就可以使用联合 _.union(

我基本上在mongo中使用$all操作符,我得到的输入可能是数组或单个元素,如下所示。那么,如何使用下划线将所有元素放在一个数组中,然后

userId = 'a';
userIds = ['a', 'b', 'c'];
otherId = ['a'] or 'a';
searchArray = [userId, userIds, otherId]
db.collections.find({userIds: {$all: searchArray}})

只要是数组,就可以使用联合

_.union(arrays) 

var userId = ['a'],
    userIds = ['a', 'b', 'c'];
    otherId = ['a'],

searchArray = _.union(userId, userIds, otherId);

不需要下划线,您可以使用concat:

var userId = ['a'],
    userIds = ['a', 'b', 'c'],
    otherId = ['a'];

var arr = userId.concat(userIds, otherId)
即使其中一个不是数组,而是一个数字或字符串,这也会起作用。此处的工作示例:


如果不保证所有变量都是数组,那么您可能需要
展平
方法

userId = 'a'; // strings
userIds = ['a', 'b', ['c']]; // multidimensional array
otherId = ['a']; // single dimensional array
searchArray = _.flatten([userId, userIds, otherId]);
db.collections.find({userIds: {$all: searchArray}})