Arrays 在Angular中,如何循环两个数组来填充第三个数组?
我使用forEach循环两个数组(蛋糕和糖霜)。警报确认了预期结果。 如何将结果添加到第三个阵列?(cakeOptions) 这把小提琴展示了迄今为止的作品: 谢谢Arrays 在Angular中,如何循环两个数组来填充第三个数组?,arrays,angularjs,foreach,Arrays,Angularjs,Foreach,我使用forEach循环两个数组(蛋糕和糖霜)。警报确认了预期结果。 如何将结果添加到第三个阵列?(cakeOptions) 这把小提琴展示了迄今为止的作品: 谢谢 function CakeController($scope) { $scope.cakes = [{ name: 'chocolate', 'price': 6 }, { name: 'yellow', 'price': 5 }, { name: 'coconut', 'price
function CakeController($scope) {
$scope.cakes = [{
name: 'chocolate',
'price': 6
}, {
name: 'yellow',
'price': 5
}, {
name: 'coconut',
'price': 7
}
];
$scope.frostings = [{
'name': 'chocolate',
'price': 5
},
{
'name': 'vanilla',
'price': 5
}, {
'name': 'coconut',
'price': 8
}];
$scope.cakeOptions = [];
angular.forEach($scope.cakes, function (value, key) {
var thisCake = JSON.stringify(value.name);
angular.forEach($scope.frostings, function (value) {
var thisFrosting = JSON.stringify(value.name, value.value);
alert(thisCake + ' cake with ' + thisFrosting + ' frosting');
我已经创建了一个新的小提琴,它实际上可以工作,并添加了一个从组合数组填充第三个方框的示例: HTML
<div ng-app="cakeApp">
<div ng-controller="cakeCtrl">
<div id="one"><strong>Cakes</strong><br>
<div class="order" ng-repeat="cake in cakes">
{{cake.name}}
</div>
</div>
<div id="two"><strong>Frostings</strong><br>
<div class="order" ng-repeat="frosting in frostings">
{{frosting.name}}
</div>
</div>
<div id="three"><strong>Combinations</strong><br>
<div class="order" ng-repeat="cakeOption in cakeOptions">
{{cakeOption}}
</div>
</div>
</div>
</div>
在内部foreach循环中,只需将
thisCake
和thismrostating
推入cakeOptions
数组。谢谢Mohammed。添加:$scope.cakeOptions.push({Cake:thisCake,Frosting:thismrosting})代码>工作正常。(不确定早期尝试失败的原因)也更新了小提琴。
var app = angular.module('cakeApp', []);
app.controller('cakeCtrl', ['$scope', function($scope) {
$scope.cakes = [{
name: 'chocolate',
price: 6
}, {
name: 'yellow',
price: 5
}, {
name: 'coconut',
price: 7
}];
$scope.frostings = [{
'name': 'chocolate',
'price': 5
},
{
'name': 'vanilla',
'price': 5
}, {
'name': 'coconut',
'price': 8
}];
$scope.cakeOptions = [];
angular.forEach($scope.cakes, function (value, key) {
var thisCake = JSON.stringify(value.name);
angular.forEach($scope.frostings, function (value) {
var thisFrosting = JSON.stringify(value.name, value.value);
$scope.cakeOptions.push(thisCake + ' cake with ' + thisFrosting + ' frosting');
});
});
}]);