简体   繁体   中英

How do i push a variable after using split function in javascript?

error: Uncaught (in promise) TypeError: Cannot read property 'push' of undefined error line: " this.name[i].push(arrayData[0]); "

I do not understand since the line before console.log("data is loaded:" + arrayData[0]); is working!

Is it something about async? Can someone please help me out?

Here is my code:

 data: {
    name: []
  },
  methods: {
    LoadData: function() {
      console.log("onload fundtion. \n");
      fetch('http://localhost/store/skininfor.txt')
        .then(response => response.text())
        .then((data) => {
          //  console.log(data);
          var textByLine = data.split("\n");
          for (var i = 0; i < textByLine.length; i++) {
            var arrayData = textByLine[i].split(",");
            console.log("data is loaded:" + arrayData[0]);
            if (arrayData[0] !== undefined) {
               this.name[i].push(arrayData[0]);
            }
          }
        });
    },

By this way this.name[i].push(arrayData[0]); you are trying to push an element into another element this is why you have that error.

this.name is the tab and this.name[i] is one element so it should be this.name.push(arrayData[0]);

您在名称数组中没有任何元素,因此您应该像这样推送。

this.name.push(arrayData[0]);

You probably need to assign instead of pushing, ie

this.name[i] = arrayData[0];

(Although I can't be sure. If you defined example input data and desired output, that would be helpful).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM