gpt4 book ai didi

JavaScript:将一个数组中的值分配给另一个数组中的变量

转载 作者:行者123 更新时间:2023-12-03 11:54:08 25 4
gpt4 key购买 nike

我想用数组('contentStrings')中的值填充一系列字符串(beijingString、belingString 等);这样就不必这样做:

beijingString = 'five strings';
berlinString = 'similar but different five strings';
bronxString = 'also similar but different five strings';
buenosairesString = 'similar again but subtly different five strings';

最后我有 40 个这样的字符串需要填充。

我尝试将城市的字符串变量名称放入第二个数组(“cities”)中并循环遍历,分配索引值。

但是它不起作用。

我是否必须以某种方式“引用”(?)每个变量作为“城市”数组的元素?

TIA!

完整代码片段:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var beijingContentString = '';
var berlinContentString = '';
var bronxContentString = '';
var buenos_airesContentString = '';
var contentStrings = [
['http://www.beijing.com',
'Beijing title',
'<img src="./images/beijing.jpg">',
'Beijing caption',
'Beijing description'
],
['http://www.berlin.com',
'Berlin title',
'<img src="./images/berlin.jpg">',
'Berlin caption',
'Berlin description'
],
['http://www.bronx.com',
'Bronx title',
'<img src="./images/Bronx.jpg">',
'Bronx caption',
'Bronx description'
],
['http://www.buenosaires.com',
'Buenos Aires title',
'<img src="./images/Buenos Aires.jpg">',
'Buenos Aires caption',
'Buenos Aires description'
]
];

var beijingString = '';
var berlinString = '';
var bronxString = '';
var bueonosairesString = '';

alert ('before: ' + beijingString);
alert ('before: ' + berlinString);
alert ('before: ' + bronxString);
alert ('before: ' + bueonosairesString);

var cities = [beijingString, berlinString, bronxString, bueonosairesString];
var contentArrayLoop = 0;
for (contentArrayLoop = 0; contentArrayLoop < 4; contentArrayLoop++) {
cities[contentArrayLoop]=
contentStrings[contentArrayLoop][0] +
contentStrings[contentArrayLoop][1] +
contentStrings[contentArrayLoop][2] +
contentStrings[contentArrayLoop][3] +
contentStrings[contentArrayLoop][4]
;
alert(cities[contentArrayLoop]);
};

alert ('after: ' + beijingString);
alert ('after: ' + berlinString);
alert ('after: ' + bronxString);
alert ('after: ' + bueonosairesString);

</script>
</body>
</html>

最佳答案

这里有一个更好的例子: http://jsfiddle.net/L1dpt0bs/1/

您不需要对城市使用任何静态数组。

var contentArrayLoop = 0;

for (contentArrayLoop = 0; contentArrayLoop < 4; contentArrayLoop++) {
var city = contentStrings[contentArrayLoop][1]
city = city.substring(0, city.indexOf(' '));
window[city + 'string'] = contentStrings[contentArrayLoop].join('');
};

alert ('after: ' + Beijingstring);
alert ('after: ' + Berlinstring);
alert ('after: ' + Bronxstring);
alert ('after: ' + Bueonosairesstring);

关于JavaScript:将一个数组中的值分配给另一个数组中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676963/

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