Javascript 检查object.property的值是value1还是value2
我在寻找一个解决方案来检查labelKey房产的价值是出租还是出售 有条件的话,我们可以这样做:Javascript 检查object.property的值是value1还是value2,javascript,object,ecmascript-6,lodash,Javascript,Object,Ecmascript 6,Lodash,我在寻找一个解决方案来检查labelKey房产的价值是出租还是出售 有条件的话,我们可以这样做: if (this.project.currentProduct.productStatus.labelKey === ('to_be_rented' || 'to_be_put_on_sale')) { } 但它不起作用,我也在寻找一种更复杂的替代方法,例如使用Lodash或es2015 我该怎么做呢?你的情况是这样的: 表达“出租”、“出售”的结果是“总是出租”。 你把那个labelKey比作
if (this.project.currentProduct.productStatus.labelKey === ('to_be_rented' || 'to_be_put_on_sale')) {
}
但它不起作用,我也在寻找一种更复杂的替代方法,例如使用Lodash或es2015
我该怎么做呢?你的情况是这样的: 表达“出租”、“出售”的结果是“总是出租”。 你把那个labelKey比作租来的。 正确的解决方案是将labelKey与两个字符串进行比较:
let labelKey = this.project.currentProduct.productStatus.labelKey;
if (labelKey === 'to_be_rented' || labelKey === 'to_be_put_on_sale')) {
...
}
通过ES2016,可以简化:
let values = ['to_be_rented', 'to_be_put_on_sale'];
if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
...
}
你的情况是这样的: 表达“出租”、“出售”的结果是“总是出租”。 你把那个labelKey比作租来的。 正确的解决方案是将labelKey与两个字符串进行比较:
let labelKey = this.project.currentProduct.productStatus.labelKey;
if (labelKey === 'to_be_rented' || labelKey === 'to_be_put_on_sale')) {
...
}
通过ES2016,可以简化:
let values = ['to_be_rented', 'to_be_put_on_sale'];
if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
...
}
您可以将所有变体放在一个阵列中,并在ES5中使用它:
const variants = ['to_be_rented', 'to_be_put_on_sale'];
const labelKey = this.project.currentProduct.productStatus.labelKey;
if (variants.indexOf(labelKey) !== -1) {
...
}
或者在ES2016中:
if (variants.includes(labelKey)) {
...
}
当您有两个以上的变体时,这些方法更方便
对于您的案例,Array.prototype.indexOf和Array.prototype.includes将是相同的,但您可以查看这些函数之间的差异。您可以将所有变体放在一个数组中,甚至在ES5中使用:
const variants = ['to_be_rented', 'to_be_put_on_sale'];
const labelKey = this.project.currentProduct.productStatus.labelKey;
if (variants.indexOf(labelKey) !== -1) {
...
}
或者在ES2016中:
if (variants.includes(labelKey)) {
...
}
当您有两个以上的变体时,这些方法更方便
对于您的案例,Array.prototype.indexOf和Array.prototype.includes将是相同的,但这些函数之间的差异您可以检查。您可以使用数组,并检查数组中是否存在该值
const values = ['to_be_rented', 'to_be_put_on_sale'];
if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
// do something
}
可以使用数组并检查数组中是否存在该值
const values = ['to_be_rented', 'to_be_put_on_sale'];
if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
// do something
}
洛达斯方式:
var toFind = this.project.currentProduct.productStatus.labelKey;
if(_.find(['to_be_rented', 'to_be_put_on_sale'], toFind)) {
// do something
}
洛达斯方式:
var toFind = this.project.currentProduct.productStatus.labelKey;
if(_.find(['to_be_rented', 'to_be_put_on_sale'], toFind)) {
// do something
}
或者使用['…','…'].includestr与ES2016。或者使用['…','…'].includestr与ES2016。