Javascript数组——将两个数组合并为一个数组

时间:2020-12-31 12:18:20

I have two arrays, one with name of the country and one with the currency type. I would like to merge these together and use the country key instead of the currencies array. What would be the best way to accomplish this?

我有两个数组,一个带有国家名称,另一个带有货币类型。我想把它们合并在一起,使用国家键而不是货币数组。实现这一目标的最佳方式是什么?

This is what my code looks like now:

这就是我现在的代码:

var country = new Array();
country["SEK"] = 'Sweden';
country["USD"] = 'United states';
var currencies = ["SEK","USD"];
var options = '';

for (var i = 0; i < currencies.length; i++) {
    options += '<option value="' + currencies[i] + '" id="' + currencies[i] + '">' + currencies[i] + ' (' + country[currencies[i]] + ')</option>';
}

3 个解决方案

#1


1  

It seem uncomfortable to use arrays. Use json object json.orgwikipedia instead, this way you can take advantage of the relation key-value. In addition you can also validate it with lint. No jQuery needed. So this is the code:

使用数组似乎不太舒服。使用json对象json.org wikipedia代替,这样您就可以利用关系键值。此外,您还可以使用lint验证它。不需要jQuery。这就是代码:

var currency = {
    "SEK": "Sweden",
    "USD": "United states",
    "GBP": "United Kingdom"
};

(function(obj) {
    var myselect = document.getElementById("currency");
    for (var key in obj) {
        var optElement = new Option( key+ " ( " + obj[key] + " ) ", key );
        optElement.id = key; //optElement.setAttribute ( "id", key);
        myselect.add ( optElement, null);
    }
})(currency);

​As for the function - I think it is better to do it with objects, instead of making a string and then adding it to the select. It is an anonymous function, so it is self-contained and won't interfere with any other code. Just use it after the select is created, or place it at the end of the page.

至于函数——我认为最好是用对象来完成,而不是创建一个字符串然后添加到select中。它是一个匿名函数,因此它是自包含的,不会干扰任何其他代码。在创建select之后使用它,或者将它放在页面的末尾。

And jsfiddle example

jsfiddle例子

Edit:

编辑:

Using add() or innerHTML - in Chrome, innerHTML is not working. And it is better this way.

使用add()或innerHTML -在Chrome中,innerHTML不工作。这样更好。

As for the removing of the options - there is remove() method. Use one of those:

至于删除选项——有remove()方法。使用其中的一个:

var x = document.getElementById("currency");
for ( var i = x.length; i > 0; i-- ) { x.remove ( 0 ); }

or

while ( x.length > 0 )               { x.remove ( x.length - 1 ); }

#2


3  

It's a common misconception that you can just use this:

这是一个常见的误解,你可以用这个:

for (var currency in country) {
  result += { ... something done with both currency and country[currency] ... };
}

The catch here is that hash is technically unordered in JS, so you cannot guarantee the same order of these options.

这里的问题是,在JS中哈希在技术上是无序的,因此您不能保证这些选项的顺序相同。

The common alternative is using array of objects instead:

常用的替代方法是使用对象数组:

var countriesData = [
{
  country: 'Sweden',
  currency: 'SEK'
},
{
  country: 'United States',
  currency: 'USD'
}
];
for (var i = 0, l = countriesData.length; i < l; i++) {
  result += { something of countriesData[i].currency and countriesData[i].country };
}


As a sidenote, consider this...

var country = new Array();
country["SEK"] = 'Sweden';
country["USD"] = 'United states';
console.log(country.length); // wait, what?

... and 0 will be logged, not 2 - as probably expected. Again, there's no such thing as 'PHP-like associative array' in JS: there are objects and arrays (which are technically objects too; typeof country will give you 'object' string).

…0将被记录,而不是2 -可能是预期的那样。同样,JS中没有类似于php的关联数组,有对象和数组(技术上也是对象);类型的国家将给你'对象'字符串)。

So this is what happens here: you create an Array object, and it inherits all the properties of Array.prototype (such as length), in particular. Now you extend this Array with two properties - 'SEK' and 'USD'; but it's not the same as pushing these strings into array with push or some similar methods! That's why its length stays the same, introducing chaos and confusion. )

这就是这里所发生的:你创建一个数组对象,它继承了数组的所有属性。特别是原型(如长度)。现在您可以使用两个属性扩展这个数组——SEK和USD;但这与push或类似的方法将这些字符串推入数组是不一样的!这就是为什么它的长度保持不变,引入混乱和混乱。

#3


2  

Try this:

试试这个:

var countries = {
    'Sweden': 'SEK',
    'United Stated': 'USD'
}, options = '', country;

for(country in countries) {
    options += '<option value="' + countries[country] + '" id="' + countries[country] + '">' + countries[country] + ' (' + country + ')</option>';
}

#1


1  

It seem uncomfortable to use arrays. Use json object json.orgwikipedia instead, this way you can take advantage of the relation key-value. In addition you can also validate it with lint. No jQuery needed. So this is the code:

使用数组似乎不太舒服。使用json对象json.org wikipedia代替,这样您就可以利用关系键值。此外,您还可以使用lint验证它。不需要jQuery。这就是代码:

var currency = {
    "SEK": "Sweden",
    "USD": "United states",
    "GBP": "United Kingdom"
};

(function(obj) {
    var myselect = document.getElementById("currency");
    for (var key in obj) {
        var optElement = new Option( key+ " ( " + obj[key] + " ) ", key );
        optElement.id = key; //optElement.setAttribute ( "id", key);
        myselect.add ( optElement, null);
    }
})(currency);

​As for the function - I think it is better to do it with objects, instead of making a string and then adding it to the select. It is an anonymous function, so it is self-contained and won't interfere with any other code. Just use it after the select is created, or place it at the end of the page.

至于函数——我认为最好是用对象来完成,而不是创建一个字符串然后添加到select中。它是一个匿名函数,因此它是自包含的,不会干扰任何其他代码。在创建select之后使用它,或者将它放在页面的末尾。

And jsfiddle example

jsfiddle例子

Edit:

编辑:

Using add() or innerHTML - in Chrome, innerHTML is not working. And it is better this way.

使用add()或innerHTML -在Chrome中,innerHTML不工作。这样更好。

As for the removing of the options - there is remove() method. Use one of those:

至于删除选项——有remove()方法。使用其中的一个:

var x = document.getElementById("currency");
for ( var i = x.length; i > 0; i-- ) { x.remove ( 0 ); }

or

while ( x.length > 0 )               { x.remove ( x.length - 1 ); }

#2


3  

It's a common misconception that you can just use this:

这是一个常见的误解,你可以用这个:

for (var currency in country) {
  result += { ... something done with both currency and country[currency] ... };
}

The catch here is that hash is technically unordered in JS, so you cannot guarantee the same order of these options.

这里的问题是,在JS中哈希在技术上是无序的,因此您不能保证这些选项的顺序相同。

The common alternative is using array of objects instead:

常用的替代方法是使用对象数组:

var countriesData = [
{
  country: 'Sweden',
  currency: 'SEK'
},
{
  country: 'United States',
  currency: 'USD'
}
];
for (var i = 0, l = countriesData.length; i < l; i++) {
  result += { something of countriesData[i].currency and countriesData[i].country };
}


As a sidenote, consider this...

var country = new Array();
country["SEK"] = 'Sweden';
country["USD"] = 'United states';
console.log(country.length); // wait, what?

... and 0 will be logged, not 2 - as probably expected. Again, there's no such thing as 'PHP-like associative array' in JS: there are objects and arrays (which are technically objects too; typeof country will give you 'object' string).

…0将被记录,而不是2 -可能是预期的那样。同样,JS中没有类似于php的关联数组,有对象和数组(技术上也是对象);类型的国家将给你'对象'字符串)。

So this is what happens here: you create an Array object, and it inherits all the properties of Array.prototype (such as length), in particular. Now you extend this Array with two properties - 'SEK' and 'USD'; but it's not the same as pushing these strings into array with push or some similar methods! That's why its length stays the same, introducing chaos and confusion. )

这就是这里所发生的:你创建一个数组对象,它继承了数组的所有属性。特别是原型(如长度)。现在您可以使用两个属性扩展这个数组——SEK和USD;但这与push或类似的方法将这些字符串推入数组是不一样的!这就是为什么它的长度保持不变,引入混乱和混乱。

#3


2  

Try this:

试试这个:

var countries = {
    'Sweden': 'SEK',
    'United Stated': 'USD'
}, options = '', country;

for(country in countries) {
    options += '<option value="' + countries[country] + '" id="' + countries[country] + '">' + countries[country] + ' (' + country + ')</option>';
}