【发布时间】:2019-05-15 17:09:39
【问题描述】:
这个问题很简单,但我一直找不到答案。 当我尝试将对象数组的元素重新分配给符合描述的另一个对象时,什么也没有发生,但是当我首先将元素设置为 null 然后重新分配它时,它可以工作。 这是我正在使用的对象列表:
servers = [
{
instanceType: 'medium',
name: 'Production',
status: 'stable',
started: new Date(15, 1, 2017)
},
{
instanceType: 'large',
name: 'User Database',
status: 'stable',
started: new Date(15, 1, 2017)
},
{
instanceType: 'small',
name: 'Development Server',
status: 'offline',
started: new Date(15, 1, 2017)
},
{
instanceType: 'small',
name: 'Testing Environment Server',
status: 'stable',
started: new Date(15, 1, 2017)
}
];
这是行不通的方法:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(value: any, args?: any): any {
for (const i of value) {
for (const j of value.slice(value.indexOf(i) + 1)) {
if (i.name > j.name) {
value[value.indexOf(i)] = j;
value[value.indexOf(j)] = i;
}
}
}
return value;
}
}
这是行之有效的方法:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(value: any, args?: any): any {
for (const i of value) {
for (const j of value.slice(value.indexOf(i) + 1)) {
if (i.name > j.name) {
const index1 = value.indexOf(i);
const index2 = value.indexOf(j);
value[index1] = null;
value[index2] = null;
value[index1] = j;
value[index2] = i;
}
}
}
return value;
}
}
这不是一个严重的问题,但我现在很好奇为什么它不能以一种方式工作,而是以另一种方式工作。 感谢您的宝贵时间!
编辑 1: 将 (i.name[0] > j.name[0]) 更改为 (i.name > j.name) 以保持一致性。两次检查都给出了相同的结果。
【问题讨论】:
标签: javascript angular typescript angular7