every 方法:用于检测数组中的所有元素是否满足指定的条件(返回值为布尔值)。如果数组中的每个元素都满足条件,则 every 方法返回 true,否则返回 false。
if (array.length) {
const propertyPortCode = 'portCode';
const propertyMktName = 'mktName';
const propertySettFact = 'settFact';
const propertyDvPlatName = 'dvPlatName';
const allValuesEqual = array.every((item, index, arr) => {
if (index === 0) {
return true; // 第一个元素默认为相等,直接返回 true
}
return (
item[propertyPortCode] === arr[index - 1][propertyPortCode] &&
item[propertyMktName] === arr[index - 1][propertyMktName] &&
item[propertySettFact] === arr[index - 1][propertySettFact] &&
item[propertyDvPlatName] === arr[index - 1][propertyDvPlatName]
);
});
if (allValuesEqual) {
console.log(`数组中的属性值互相相等。`);
} else {
console.log(`数组中的属性值不互相相等。`);
}
}
- 使用
reduce 方法来实现
if (array.length) {
const propertyPortCode = 'portCode';
const propertyMktName = 'mktName';
const propertySettFact = 'settFact';
const propertyDvPlatName = 'dvPlatName';
const allValuesEqual = array.reduce((result, item, index, arr) => {
if (index === 0) {
return true; // 第一个元素默认为相等,直接返回 true
}
return (
result &&
item[propertyPortCode] === arr[index - 1][propertyPortCode] &&
item[propertyMktName] === arr[index - 1][propertyMktName] &&
item[propertySettFact] === arr[index - 1][propertySettFact] &&
item[propertyDvPlatName] === arr[index - 1][propertyDvPlatName]
);
}, true);
if (allValuesEqual) {
console.log(`数组中的属性值互相相等。`);
} else {
console.log(`数组中的属性值不互相相等。`);
}
}