我有2个阵列基本上是国家和颜色,我想绑定两个数组的每个项目。我试过一个功能,但没有工作......
function mapColor(){
var countries = ["UK", "INDIA", "FRANCE", "CHINA"];
var colors = ["#807dba", "#41ab5d", "#DECF3F", "#FAA43A"];
var obj ={};
for(i=0, j=0; i<countries.length; i++, j<colors.length, j++){
obj[countries[i]] = colors[j];
}
return obj;
};
和预期的对象应该是。
{"UK":"#807dba","INDIA":"#41ab5d","FRANCE":"#DECF3F","CHINA":"#FAA43A"}
答案 0 :(得分:1)
你太复杂了。
for (i=0; i<countries.length; i++){
obj[countries[i]] = colors[i];
}
或
countries.forEach( function (val, ind){ obj[val] = colors(ind); });
答案 1 :(得分:1)
您可以使用reduce
之类的:
function mapColor(){
var countries = ["UK", "INDIA", "FRANCE", "CHINA"],
colors = ["#807dba", "#41ab5d", "#DECF3F", "#FAA43A"];
return countries.reduce(function(obj, country, index){
obj[country] = colors[index];
return obj;
}, {});
};
reduce()
方法对累加器和每个应用函数 数组的值(从左到右)必须将其减少为单个 值。
答案 2 :(得分:1)
由于您在同一个函数中定义数组,为什么不执行以下操作:
function mapColor() {
var obj = {};
obj['UK'] = '#807dba';
...
return obj;
}
或者如果要传入数组,那么:
假设数组总是应该具有相同的长度:
function mapColor(countries, colors) {
var obj = {};
if (countries.length != colors.length) {
alert('Countries and Colors array should be of the same length');
return null;
}
for (var i = 0; i < countries.length; i++) {
obj[countries[i]] = colors[i];
}
return obj;
}
如果不能保证它们的长度相同:
function mapColor(countries, colors) {
var minLength = Math.min(countries.length, colors.length),
obj = {};
for (var i = 0; i < minLength; i++) {
obj[countries[i]] = colors[i];
}
return obj;
}
答案 3 :(得分:0)
Public Class GuideEntry
Public Property eventId As Integer
Public Property episodeId As Integer
Public Property serieslinkId As Integer
Public Property serieslinkUri As String
Public Property channelName As String
Public Property channelUuid As String
Public Property channelNumber As String
Public Property start As Integer
<JsonProperty("stop")> _
Public Property stopValue As Integer 'JSON value causing the problem
Public Property title As String
Public Property description As String
Public Property genre As Integer()
Public Property nextEventId As Integer
Public Property episodeUri As String
Public Property episodeNumber As Integer
Public Property episodeOnscreen As String
Public Property subtitle As String
Public Property partNumber As Integer
Public Property partCount As Integer
Public Property starRating As Integer
End Class