猿问

函数内的Javascript for循环不推送到数组

编辑 - 包括计算 refill_playlist_len 的代码


我在 Javascript 中有一个函数,它删除 HTML 表的一行并用数组中的值再次填充它。


在这个 deleteRow 函数中,我有一个 for 循环,它遍历一个字符串并将部分字符串分配给不同的变量,并尝试将它们推送到数组中。


没有for循环,它可以正常工作(即当我手动索引时),但由于某种原因,当我将它放在 for 循环中时,值不会被推送到数组中。这些值本身在每次迭代时都打印得很好,只是没有添加到数组中。


Refill_playlist_len 是 Django Queryset (30) 的计数。



var refill_playlist_len = '{{ playlist.count }}';


var artist_Arr = [];

var track_Arr = [];

var track_id_Arr = [];

var album_Arr = [];

var artist_name;

var track_name;

var track_id;

var album_name;


for (var i = 0; i < refill_playlist_len; i++) {

      var searchStr = refill_playlist[i];

      console.log(searchStr);

      console.log(typeof searchStr);

      console.log(typeof refill_playlist);


      //grab variables

      artist_name = searchStr.match(new RegExp("artist_name:" + "(.*)" + ", album_name:"));

      console.log(artist_name[1]);

      artist_Arr.push(artist_name[1]);


      track_name = searchStr.match(new RegExp("track_name:" + "(.*)" + ", acousticness:"));

      console.log(track_name[1]);

      track_Arr.push(track_name[1]);


      track_id = searchStr.match(new RegExp("track_id:" + "(.*)" + ", track_name:"));

      console.log(track_id[1]);

      track_id_Arr.push(track_id[1]);


      album_name = searchStr.match(new RegExp("album_name:" + "(.*)" + ", track_number:"));

      console.log(album_name[1]);

      album_Arr.push(album_name[1]);

    }

控制台日志如下图所示。您可以看到打印的“searchStr”的一部分,以及数据类型、艺术家姓名、曲目 ID 等,但由于某种原因,它说“searchStr”未定义?

我对 Javascript 很陌生,所以如果我忘记了一些基本的东西,我深表歉意。


有只小跳蛙
浏览 94回答 1
1回答

哈士奇WWW

代码的多个问题。请清理代码。示例如下。function find(refill_playlist) {&nbsp; const refill_playlist_len = refill_playlist.length&nbsp; let artist_Arr = []&nbsp; let track_id_Arr = []&nbsp; let track_Arr = []&nbsp; let album_Arr = []&nbsp; for (i = 0; i < refill_playlist_len; i++) {&nbsp; &nbsp; var searchStr = refill_playlist[i];&nbsp; &nbsp; if(!searchStr) continue;&nbsp; &nbsp; //grab variables&nbsp; &nbsp; artist_name = searchStr.match(/artist_name:(.*), album_name:/);&nbsp; &nbsp; artist_name && artist_Arr.push(artist_name[1]);&nbsp; &nbsp; track_name = searchStr.match(/track_name:(.*), acousticness:/);&nbsp; &nbsp; track_name && track_Arr.push(track_name[1]);&nbsp; &nbsp; track_id = searchStr.match(/track_id:(.*), track_name:/);&nbsp; &nbsp; track_id && track_id_Arr.push(track_id[1]);&nbsp; &nbsp; album_name = searchStr.match(/album_name:(.*), track_number:/);&nbsp; &nbsp; album_name && album_Arr.push(album_name[1]);&nbsp; }&nbsp; console.log(artist_Arr)&nbsp; console.log(track_id_Arr)&nbsp; console.log(track_Arr)&nbsp; console.log(album_Arr)}find(&nbsp; [&nbsp; &nbsp; `&nbsp; &nbsp; artist_name: test, album_name:&nbsp; &nbsp; `,&nbsp; &nbsp; null&nbsp; ])
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答