ES6与ES5中的set等效 [英] Equivalent of set in ES6 to ES5
问题描述
我有一个要在ES6中进行迭代的集合.我正在尝试将其转换为ES5中的等效版本.由于ES6,我的构建失败了.这就是为什么我将其转换为ES5.
I have a set over which I am iterating in ES6. I am trying to convert it to its equivalent in ES5. My build is getting failed because of ES6. That's why I am converting it to ES5.
这是我在ES6中的代码
Here's my code in ES6
service.getDevices = function (date) {
var result = [];
var deviceList = devices[date.getTime()];
for (let item of deviceList) { // browser compatibility: support for ECMA6
result.push({"deviceName": item});
}
return result;
}
由于"let",我遇到了错误.我尝试使用for (var item in deviceList)
,它不显示图表.
I am getting error because of 'let'. I tried using for (var item in deviceList)
, it does not display the charts.
我也尝试过:
for(var i = 0; i < deviceList.length(); i++){
result.push({"deviceName" : deviceList[i]});
}
即使这不适用于set.有人可以帮我告诉我如何遍历ES5中的集合吗?如果那不可能,是否有任何等效的方法呢?
Even this is not working for set. can someone help and tell me how to iterate over a set in ES5 and if that is not possible, is there any equivalent way of doing it?
推荐答案
我认为第二个for
示例的问题只是length
是属性而不是函数,因此您不应该添加()
到最后一个有效的版本可能如下所示:
I think your problem with your second for
example is just that length
is a property and not a function so you shouldn't add ()
to the end of it. A working version of this might look like this:
for(var i = 0; i < deviceList.length; i++){
result.push({"deviceName" : deviceList[i]});
}
这假定(如 @grabantot 指出)deviceList
是一个数组,但是,如果它是一个Set
,那么您需要使用deviceList.size
属性.
This assumes (as @grabantot pointed out) that deviceList
is an array, however, if it's a Set
then you need to use the deviceList.size
property.
但是,第一个for
循环有一个更兼容的版本,它是forEach()
函数(可在设置),如下所示:
However, there is a more compatible version of your first for
loop which is the forEach()
function (which is available on Array and Set), like this:
deviceList.forEach(function (item) {
result.push({"deviceName": item});
});
这篇关于ES6与ES5中的set等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!