我有四个动态输入。用户选择想要多少。
在输入中,他输入商品ID,成功后,我将其发送到URL。
网址只能有两个或三个或四个ID

'http://someurl/' + ID + '/someParams'
example: 'http://someurl/991,992,993,994/someParams'


我将ID从html传递给控制器

$scope.submitChoice = function (name) {
    $scope.choices.forEach(function(choice, index){
        if(choice.name)
        {
            switch (index) {
                case 0:
                    var firstId = choice.name;
                    break;
                case 1:
                    var secondId = choice.name;
                    break;
                case 2:
                    var thirdId = choice.name;
                    break;
                case 3:
                    var fourthId = choice.name;
                    break;
            }
            console.log(firstId, secondId, thirdId, fourthId);
            $scope.getBenchIdForCompare(firstId, secondId, thirdId,fourthId);
        }
    })
}


我使用SWITCH CASEINDEX是因为我需要将每个ID都设置为唯一var(因为我的应用程序的另一部分)。
问题是,当我在输入中提交输入的ID时,我在控制台中得到该ID
    console.log(firstId, secondId, thirdId, fourthId);

安慰

991 undefined undefined undefined
undefined 992 undefined undefined
undefined undefined 993 undefined
undefined undefined undefined 994


而且我无法将此传递给另一个函数,因为我需要拥有991 992 993 994

还有其他方法可以做到这一点吗?

最佳答案

您可以改用map并创建一个array。一旦创建了array,您就可以使用join()方法将它们加入,您将获得现成的逗号分隔字符串。可以添加此逗号分隔的字符串以获得所需的URL。

$scope.submitChoice = function(name) {
  var choices = $scope.choices.map(function(choice){
    return choice.name;
  });
  console.log(choices.join(','));
  $scope.getBenchIdForCompare(choices[0], choices[1], choices[2], choices[3]);
}


ES6版本(使用传播运算符):

$scope.submitChoice = function(name) {
  let choices = $scope.choices.map(choice => choice.name)
  console.log(choices.join(','));
  $scope.getBenchIdForCompare(...choices);
}

07-25 23:31
查看更多