Javascript 如何使用单个元素或元素数组创建数组?
在几种语言中,编写接受数组或单个对象的方法非常常见: Ruby中的Ex:Javascript 如何使用单个元素或元素数组创建数组?,javascript,arrays,lodash,Javascript,Arrays,Lodash,在几种语言中,编写接受数组或单个对象的方法非常常见: Ruby中的Ex: def sum(array_or_single_element) # converts into array if single element, remains the same otherwise array = Array(array_or_single_element) array.reduce(:+) end 我觉得Lodash是来为JS提供这种类型的实用程序的。但它没有提供这样的方法 真的没有吗
def sum(array_or_single_element)
# converts into array if single element, remains the same otherwise
array = Array(array_or_single_element)
array.reduce(:+)
end
我觉得Lodash是来为JS提供这种类型的实用程序的。但它没有提供这样的方法
- 真的没有吗
- 是不是JS中的ovbious(在这种情况下,我错过了它)太多了,所以它不需要在框架中
if (typeof array === 'Array') {
//
}
你可以这样用
console.log([].concat(0));
// [ 0 ]
console.log([].concat([1, 2, 3]));
// [ 1, 2, 3 ]
console.log([].concat("thefourtheye"));
// [ 'thefourtheye' ]
我们用一个空数组连接所有需要的元素。因此,即使我们的原始数据只是一个元素,它也将成为新数组的一部分。Nice,不知道concat可以使用单个元素!