[英]How to use each(..) function in typescript?
_.each(key_val, function(e){
if($.inArray(e[0], names) == -1){
var node = {};
node.name = e[0];
if(e[1]) {
node.value = e[1];
node.symbolSize = e[1] * nodeProp;
}
optionNodes.push(node);
names.push(e[0]);
}
});
Above code from used angular.js I have to incorporate in angular typescript.以上代码来自使用过的 angular.js 我必须合并到 angular typescript 中。 here is "key_val" is array
这里是“key_val”是数组
forEach() method calls a function for each element in the array. forEach() 方法为数组中的每个元素调用 function。
Syntax is as follows,语法如下,
array.forEach(callback[, thisObject]);
where,在哪里,
callback − Function to test for each element.回调- Function 测试每个元素。
thisObject − Object to use as this when executing callback. thisObject - Object 在执行回调时用作 this。
Example:例子:
let num = [7, 8, 9];
num.forEach(function (value) {
console.log(value);
});
On compiling, it will generate the following JavaScript code编译时会生成如下 JavaScript 代码
var num = [7, 8, 9];
num.forEach(function (value) {
console.log(value);
});
Its output is as follows其output如下
7
8
9
To achieve what your function is doing, you can create an array of object with name & value keys like this -要实现您的 function 正在执行的操作,您可以使用如下名称和值键创建 object 数组 -
let key_val = [{name: 'c', value: 'xyz'}, {name: 'd', value: ''}];
Assuming you also have an array of names like -假设您还有一系列名称,例如 -
let names = ['a', 'b'];
To iterate over each object in key_val array, you can use map like this -要遍历 key_val 数组中的每个 object,您可以像这样使用 map -
key_val.map(item => {
if(names.indexOf(item.name) === -1) { //checking if item.name is present in names array or not
var node = {};
node.name = item.name;
if(item.value) {
node.value = item.name;
node.symbolSize = item.name * nodeProp;
}
optionNodes.push(node);
names.push(item.name);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.