如果输入是JavaScript中的数组数组,如何传播参数

AJ *_*ani 3 javascript node.js

试图将数组作为参数传播到节点中的join方法path,但没有运气:

var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
paths.push(userInput);
var target = path.join.apply(null, paths);
Run Code Online (Sandbox Code Playgroud)

我明白了:

TypeError:path.join的参数必须是字符串

一种可能的解决方案是给方法一串参数.我甚至不知道这是否可能.但只是好奇,如果在这种情况下JavaScript中有一个技巧.或者我接近它完全错了?

小智 11

您正在将数组推送到数组上,从而产生

[ __dirname, [ 'app', 'js' ] ]
Run Code Online (Sandbox Code Playgroud)

path.join不知道如何处理这些嵌套数组.apply不会以某种方式神奇地压扁其输入.来自的错误消息path.join不能更清楚:它希望它的参数是字符串,而不是数组.所以改为使用concat组合数组:

var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];

// Use concat here
paths = paths.concat(userInput);

var target = path.join.apply(null, paths);
Run Code Online (Sandbox Code Playgroud)

另一种选择

paths.push.apply(paths, userInput);
Run Code Online (Sandbox Code Playgroud)

这会把元素一个一个地推userInputpaths一边.

如果您使用的是ES6,那么您可以使用spread运算符并将其写为:

paths.push(...userInput)
Run Code Online (Sandbox Code Playgroud)

要么

paths = [...paths, ...userInput]
Run Code Online (Sandbox Code Playgroud)

或直接

var target = path.join(...paths, ...userInput)
Run Code Online (Sandbox Code Playgroud)