我正在处理一个javascript问题,要求我:
编写一个函数,将数组(第一个参数)拆分为大小(第二个参数)的长度,并将它们作为多维数组返回.
例如,输入
chunk([0, 1, 2, 3, 4, 5], 2)
Run Code Online (Sandbox Code Playgroud)
应该返回'chunked arrays':[[0,1],[2,3],[4,5]]
我可以让它适用于大多数示例,但当有超过2个块时,它会切换顺序,我不知道为什么.这是我写的代码:
function chunk(arr, size) {
var newArray = [],
i, temp = arr;
for (i = 0;i<= arr.length-size;i+=size){
newArray.push(arr.slice(i,i+size));
temp.splice(i,size);
}
newArray.push(temp);
return newArray;
}
chunk(['a', 'b', 'c', 'd'], 2);
Run Code Online (Sandbox Code Playgroud) 我没有使用控制器之外的范围,所以我很困惑为什么我一直得到错误:
Uncaught ReferenceError: $scope is not defined
Run Code Online (Sandbox Code Playgroud)
它来自第5行,它是"pollApp.controller"行.
(app.js)
var pollApp = angular.module('myApp', ['ui.router']);
pollApp.controller('choiceCtrl', [$scope, function ($scope) {
$scope.choices = [{body: "test"}]; //just for testing
$scope.addChoice = function () {
//add new choice
if ($scope.choiceBody) {
$scope.choices.push({
body: $scope.choiceBody
});
$scope.choiceBody = null;
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
我还检查过Angular正在加载正常.任何帮助都是极好的.谢谢.