Vue.js 判断 ID 值是否在数组中存在
可以使用`Array.prototype.includes()`方法来判断一个值是否存在于数组中。在 Vue 中,可以使用该方法来判断id值是否存在于arr1数组中。
例如,假设我们有一个 Vue 组件,其中有一个 data 属性 arr1,它是一个包含多个对象的数组。我们想要判断一个 id 值是否存在于 arr1 中,可以在 Vue 组件的`computed`属性中定义一个计算属性,然后使用`Array.prototype.includes()`来判断 id 值是否存在于 arr1 数组中。
<template>
<div>
<!-- 显示id值是否存在于arr1数组中 -->
<p>{{ isIdInArray ? 'ID exists in arr1' : 'ID does not exist in arr1' }}</p>
</div>
</template>
<script>
export default {
data() {
return {
arr1: [
{ id: 1, name: 'object1' },
{ id: 2, name: 'object2' },
{ id: 3, name: 'object3' }
],
idToCheck: 2
}
},
computed: {
isIdInArray() {
return this.arr1.map(item => item.id).includes(this.idToCheck);
}
}
}
</script>
在上面的例子中,我们定义了一个计算属性isIdInArray,它使用`Array.prototype.map()`方法将arr1数组中的每个对象的id属性提取出来,然后使用`Array.prototype.includes()`方法来判断idToCheck是否存在于提取出来的id数组中。最终,我们将计算属性的返回值用于显示id值是否存在于arr1数组中的消息。
原文地址: https://www.cveoy.top/t/topic/qs8u 著作权归作者所有。请勿转载和采集!