小编mat*_*tch的帖子

将ngFor变量传递给ngIf模板

如果使用带有then/else语法的模板,如何将ngFor循环中的当前变量传递给ngIf?

看起来它们在内联时使用时很好,但是无法从模板访问,例如:

<ul *ngFor="let number of numbers">
  <ng-container *ngIf="number % 2 == 0; then even_tpl; else odd_tpl"><>/ng-container>
</ul>


<ng-template #odd_tpl>
  <li>Odd: {{number}}</li>  
</ng-template>

<ng-template #even_tpl>
  <li>Even: {{number}}</li>  
</ng-template>
Run Code Online (Sandbox Code Playgroud)

模板似乎根本没有访问权限number,但如果内联使用它可以工作.

以下链接中的工作版和非工作版的完整示例:plunkr

angular-ng-if ng-template ngfor angular

11
推荐指数
2
解决办法
5035
查看次数

根据现有的对象/数组创建一个空的对象/数组

我正在编写一个将对象或数组作为参数的函数,我想为其创建一个新的空副本,并使用原始对象中的转换数据填充它。

我想知道是否有一种方法可以简单地制作此新对象/数组,而不必测试事物的类型并采取适当的措施。

目前,“长距离”方法是:

const transf = (thing) => {
  if (typeof(thing) === 'array') {
    const new = []
  }  else {
    const new = {}
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望有一种不错的“内置”方式可以执行以下操作:

const transf = (thing) => {
  const new = thing.emptyCopy()
}
Run Code Online (Sandbox Code Playgroud)

我已经看过了,Object.create但是它总是使一个object(即使prototype是是array),并typeof返回一个字符串,该字符串不能与eg new等一起使用。

有没有捷径可以做到这一点,或者我不走运吗?

javascript

3
推荐指数
1
解决办法
58
查看次数

有没有更简洁的方法来获取对应的字典值

用户输入宠物名称,如果在字典中找到,代码返回宠物的价格,否则要求用户尝试不同的名称。想知道这是否可以用更少的代码行以更简洁的方式完成?

pets = {'bird': 3.5, 'cat': 5.0, 'dog': 7.25, 'gerbil': 1.5}

while True:

    req_pet = input("Enter pet name: ")

    if req_pet in pets:
        for (pet, price) in pets.items():
            if pet == req_pet:
                print(price)
                exit(0)
    else:
        print("Pet not found, let's try a different one?")
Run Code Online (Sandbox Code Playgroud)

python python-3.x

0
推荐指数
1
解决办法
59
查看次数