【问题标题】:Is it possible to have an associative array in Vue.js without using an object?Vue.js 中是否可以在不使用对象的情况下拥有关联数组?
【发布时间】:2020-01-13 16:48:41
【问题描述】:
我正在尝试获取关联数组,但此语法会产生错误,如 lamda 符号。我该怎么做?我想避免使用对象,因为键必须是包含大写字母和空格的字符串。
<script>
export default {
name: 'VueHeader',
data() {
return {
links : ['Dashboard' => '/dashboard', 'Account' => '/account'],
}
}
}
</script>
【问题讨论】:
标签:
javascript
vue.js
associative-array
【解决方案1】:
<script>
export default {
name: 'VueHeader',
data() {
return {
links : {'Dashboard': '/dashboard', 'Account': '/account'},
};
}
}
</script>
JS 对象可以使用字符串作为键。这些将满足您的需求,因为'Foo' !== 'foo'。举个例子:
> x = {"foo": 10, "Foo": 20, "foo bar": 15}
{ foo: 10, Foo: 20, 'foo bar': 15 }
> x['Foo']
20
> x['foo']
10
> x['foo bar']
15
【解决方案2】:
另一个答案正确地指出,普通对象在 JavaScript 中充当关联数组:
...
links : {'My Dashboard': '/dashboard', 'My Account': '/account'},
...
键可以是任意字符串。如果密钥包含空格或其他非字母数字字符,可以使用bracket notation 访问它。由于它是基本的 JS 功能,因此在 Vue 模板中得到支持:
{{links['My Dashboard']}}
普通对象的问题在于规范不保证键的顺序,尽管它在所有当前的实现中事实上都保留了。
保证顺序的现代替代方案是 ES6 Map。它是 Vue 中的 currently non-reactive,只能用普通对象替换静态数据:
...
links : new Map([['My Dashboard', '/dashboard'], ['My Account': '/account']]),
...
【解决方案3】:
由于 javascript 中不存在关联数组,因此数组必须始终以递增顺序为其整数索引。
除此之外,您可以只创建一个对象并以数组表示法访问该属性,如下所示:
const obj = { 'Dashboard': '/dashboard', 'Account': '/account' };
console.log(obj['dashboard']);
console.log(obj['Account']);