不能替换数组中的项

Can't replace an item inside of an array

本文关键字:数组 替换 不能      更新时间:2023-09-26

编写Angular应用程序。

在此代码中,我试图替换数组中特定数字的项。

for (i=0;i<this.marked.length;i++) {
    this.index = this.marked[i].ind;
    this.newSongs[this.index] = this.marked[i].name;
}

这就是这。标记看起来像:

{
    ind: index,
    name: songName
}

那么为什么结果是这样的呢?

['name1', 2: 'name3']

代替:

['name1', 'name2', 'name3'] 

对不起,伙计们,它实际上是this.marked[i].ind;我不小心删掉了。问题没有解决

Khalid和Joel给了你正确的建议。您需要使用:

this.index = this.marked[i].ind

这里有一个angularJs提琴给你。希望这对你有帮助

https://jsfiddle.net/trollr/3adngkmx/

function SongCtrl($scope) {
  $scope.songs = [
        {
            ind: 1,
            name: "Tessie"
        },
        {
            ind: 2,
            name: "Kiss Me I’m Shitfaced"
        },
        {
            ind: 3,
            name: "The State of Massachusets"
        }
    ];
    $scope.replace = function(index, value) {
        for (i=0;i<$scope.songs.length;i++) {
            var currentIndex = $scope.songs[i].ind;
            if(currentIndex == index) {
                 $scope.songs[i].name = value;
            }
        }
    }
}

我想你只需要把

this.index = this.marked[i]

this.index = this.marked[i].ind

我注意到我试图在循环中运行我的代码。所以当我把它拔出来的时候它正常工作了。