为什么我从 vue.js 组件脚本中的一个简单的 for 循环中收到“我未定义”错误?

我正在尝试获取一个数组,按版本对该数组进行排序,然后将所有以“ipad”开头的版本移动到列表的末尾。


来自单个文件 vue.js 组件的片段:


  computed: {

    orderedUsers: function () {

      let newArray = sortBy(this.jobs, 'version').reverse()

      for (i in newArray) {

        if (i.version.startsWith('iPad')) {

          newlist.push(newlist.splice(i, 1)[0]);

        }

      }

      return newArray

  },

错误:


vue.runtime.esm.js?e832:619 [Vue warn]: Error in render: "ReferenceError: i is not defined"

不确定这是 js 问题还是 vue.js 问题


富国沪深
浏览 222回答 2
2回答

拉莫斯之舞

尝试在 for 循环中使用 let i 之前添加它。请参阅下面的示例。for (let i in newArray) {  if (i.version.startsWith('iPad')) {    newlist.push(newlist.splice(i, 1)[0]);  }}

饮歌长啸

原代码的几个问题。失踪const/let上iin循环应该是of。或者可能不是。以下几行似乎假定i既是索引又是条目。newlist&nbsp;没有定义。它似乎试图在迭代数组的同时对其进行变异。我想你正在寻找更像这样的东西。const newArray = sortBy(getData(), 'version').reverse()const nonIPads = []const iPads = []for (const entry of newArray) {&nbsp; if (entry.version.startsWith('iPad')) {&nbsp; &nbsp; iPads.push(entry)&nbsp; } else {&nbsp; &nbsp; nonIPads.push(entry)&nbsp; }}const all = [...nonIPads, ...iPads]console.log(all)function sortBy(array, property) {&nbsp; return [...array].sort((a, b) => {&nbsp; &nbsp; const valueA = a[property]&nbsp; &nbsp; const valueB = b[property]&nbsp; &nbsp; if (valueA === valueB) {&nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; return valueA < valueB ? -1 : 1&nbsp; })}function getData() {&nbsp; return [&nbsp; &nbsp; {version: 'f'},&nbsp; &nbsp; {version: 'a'},&nbsp; &nbsp; {version: 'd'},&nbsp; &nbsp; {version: 'iPad 3'},&nbsp; &nbsp; {version: 'iPad 1'},&nbsp; &nbsp; {version: 'iPad 4'},&nbsp; &nbsp; {version: 'e'},&nbsp; &nbsp; {version: 'c'},&nbsp; &nbsp; {version: 'g'},&nbsp; &nbsp; {version: 'b'},&nbsp; &nbsp; {version: 'iPad 2'}&nbsp; ]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript