[英]Can't access elements of an array
I'm still quite new to Angular and JavaScript so apologies if this is an obvious mistake. 我仍然是Angular和JavaScript的新手,所以如果这是一个明显的错误就道歉。
I have this code that selects 2 text files, then puts them into a single array. 我有这个代码,选择2个文本文件,然后将它们放入一个数组。
$scope.textArray = [];
$scope.textUpload = function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.textIsLoaded;
reader.readAsText(file);
};
};
$scope.textIsLoaded = function(e){
$scope.$apply(function() {
$scope.textArray.push(e.target.result);
});
This displays an array like: 这将显示如下数组:
["160 591 114 229","186 699 132 272"] [“160 591 114 229”,“186 699 132 272”]
When I access the array through the HTML both elements of the array are displayed and I can use split, length, etc. But if I access the array through script I can only access and change the first element. 当我通过HTML访问数组时,显示了数组的两个元素,我可以使用split,length等。但是如果我通过脚本访问数组,我只能访问和更改第一个元素。 If I try to access the second element through textArray[1]
nothing will show up, if I add textArray[1].split(' ')
it says that it cant read property of undefined. 如果我尝试通过textArray[1]
访问第二个元素,则不会显示任何内容,如果我添加textArray[1].split(' ')
它会说它无法读取undefined的属性。
I have tried using join and slice in the script to alter the array or create a new array, but they are unable to access the element as well. 我已尝试在脚本中使用join和slice来更改数组或创建新数组,但它们也无法访问该元素。 Any help with this problem would be appreciated. 任何有关此问题的帮助将不胜感激。
Edit: When I use 编辑:当我使用时
$scope.arrayOne = $scope.textArray[0].split(' ')
It works fine and outputs the correct thing, but when I use 它工作正常并输出正确的东西,但当我使用
$scope.arrayOne = $scope.textArray[1].split(' ')
It doesn't output anything. 它不输出任何东西。
Edit2: Found another question with the same problem and managed to fix it by adding 编辑2:发现另一个问题同样的问题,并设法通过添加修复它
$scope.$watch('textArray', function(){
In front of 在...前面
$scope.arrayOne = $scope.textArray[1].split(' ');
You should try and split the 你应该尝试拆分
$scope.textArray[1].split(' ');
That should work. 这应该工作。 Make sure you pass the $scope
as parameter to the method that is trying to split the textArray
. 确保将$scope
作为参数传递给尝试拆分textArray
。
This is a working example: 这是一个有效的例子:
<div ng-controller="ResultSplit">
{{result}}
</div>
And the javascript: 和javascript:
function ResultSplit($scope) {
$scope.textArray = ["1223 2233", "3344 555 6666"];
$scope.result = $scope.textArray[1].split(' ');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.