为什么我从 vue.js 组件脚本中的简单 for 循环中得到 'i is not defined' 错误?
why am i getting 'i is not defined' error from a simple for loop in vue.js component script?
我正在尝试获取一个数组,按版本对该数组进行排序,然后将所有以 '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 问题
尝试在 for 循环中使用之前添加 let i。
请参阅下面的示例。
for (let i in newArray) {
if (i.version.startsWith('iPad')) {
newlist.push(newlist.splice(i, 1)[0]);
}
}
原代码有几个问题。
i
上缺少 const
/let
in
循环应该是 of
。或者可能不是。以下几行似乎假定 i
既是索引又是条目。
newlist
未定义。
- 它似乎试图在遍历数组的同时改变它。
我想你正在寻找更像这样的东西。
const newArray = sortBy(getData(), 'version').reverse()
const nonIPads = []
const iPads = []
for (const entry of newArray) {
if (entry.version.startsWith('iPad')) {
iPads.push(entry)
} else {
nonIPads.push(entry)
}
}
const all = [...nonIPads, ...iPads]
console.log(all)
function sortBy(array, property) {
return [...array].sort((a, b) => {
const valueA = a[property]
const valueB = b[property]
if (valueA === valueB) {
return 0
}
return valueA < valueB ? -1 : 1
})
}
function getData() {
return [
{version: 'f'},
{version: 'a'},
{version: 'd'},
{version: 'iPad 3'},
{version: 'iPad 1'},
{version: 'iPad 4'},
{version: 'e'},
{version: 'c'},
{version: 'g'},
{version: 'b'},
{version: 'iPad 2'}
]
}
我正在尝试获取一个数组,按版本对该数组进行排序,然后将所有以 '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 问题
尝试在 for 循环中使用之前添加 let i。 请参阅下面的示例。
for (let i in newArray) {
if (i.version.startsWith('iPad')) {
newlist.push(newlist.splice(i, 1)[0]);
}
}
原代码有几个问题。
i
上缺少 in
循环应该是of
。或者可能不是。以下几行似乎假定i
既是索引又是条目。newlist
未定义。- 它似乎试图在遍历数组的同时改变它。
const
/let
我想你正在寻找更像这样的东西。
const newArray = sortBy(getData(), 'version').reverse()
const nonIPads = []
const iPads = []
for (const entry of newArray) {
if (entry.version.startsWith('iPad')) {
iPads.push(entry)
} else {
nonIPads.push(entry)
}
}
const all = [...nonIPads, ...iPads]
console.log(all)
function sortBy(array, property) {
return [...array].sort((a, b) => {
const valueA = a[property]
const valueB = b[property]
if (valueA === valueB) {
return 0
}
return valueA < valueB ? -1 : 1
})
}
function getData() {
return [
{version: 'f'},
{version: 'a'},
{version: 'd'},
{version: 'iPad 3'},
{version: 'iPad 1'},
{version: 'iPad 4'},
{version: 'e'},
{version: 'c'},
{version: 'g'},
{version: 'b'},
{version: 'iPad 2'}
]
}