gpt4 book ai didi

javascript - 带有 typeof 表达式的 ng-switch

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:48 27 4
gpt4 key购买 nike

所以我有一个可以是任何类型的变量。我所说的类型是指它可以是一个字符串,也可以是一个对象。我正在尝试根据类型运行不同的代码。

我的变量名为 range,它是在 JavaScript 中定义的。我试过的是。 vars 是我循环访问的对象。

<tr ng-repeat="(key, range) in vars">
<td ng-switch="typeof range">
<span ng-switch-when="string">It's a string</span>
<span ng-switch-when="object">It's an object</span>
<span ng-switch-default>It's something else</span>
</td>
</tr>

但这会抛出一个无效的表达式错误。执行此操作的最佳方法是什么?

最佳答案

试试这个...我还添加了对不同类型变量的检测:stringarrayobjectnumbernullundefined

"use strict";
angular.module('myApp', [])
.controller("myController", function() {
this.vars = {
key1: "String",
key2: "String2",
key3: 42,
key4: {
name: "Mr. Anderson"
},
key5: [1, 2, 3, 4, 5],
key6: null,
key7: undefined
};
this.getTypeOf = function(value) {
if(value === null) {
return "null";
}
if(Array.isArray(value)) {
return "array";
}
return typeof value;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<table ng-app="myApp" ng-controller="myController as ctrl">
<tr ng-repeat="(key, range) in ctrl.vars">
<td ng-switch="ctrl.getTypeOf(range)">
<div ng-switch-when="string">It's a string</div>
<div ng-switch-when="object">It's an object</div>
<div ng-switch-when="number">It's a number</div>
<div ng-switch-when="array">It's an array</div>
<div ng-switch-when="null">It's null</div>
<div ng-switch-when="undefined">It's undefined</div>
<div ng-switch-default>It's something else</div>
</td>
</tr>
</table>

关于javascript - 带有 typeof 表达式的 ng-switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320630/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com