我有两个数组,并且想要同一个句子中两个数组的元素,例如:
var a= [2,3,4,5];
var b= [12,13,14,15];
输出应该是:
- After 2 years, Alec will be 12 years old.
- After 3 years, Alec will be 13 years old.
...等
现有代码:
function newS1(){
for (var j=0; j<(a.length); j++){
console.log('After '+ a[j] +' years,');
}
}
var a= [2,3,4,5];
var b= [12,13,14,15];
function newS2(){
for (var i=0; i<(b.length); i++){
console.log('Alec will be ' +b[i]+' years old');
}
}
newS1();
newS2();
答案 0 :(得分:0)
您可以使用a
并使用array#forEach
索引迭代数组b
,遍历数组b
。使用template literals
var a= [2,3,4,5],
b= [12,13,14,15];
a.forEach((alexAge, index) => {
console.log(`After ${b[index]} years, Alec will be ${alexAge} years old.`);
});
&#13;
您可以使用单个for循环来迭代两个数组。
var a= [2,3,4,5];
var b= [12,13,14,15];
function newS1(){
for (var j = 0; j < (a.length); j++){
console.log('After '+ a[j] +' years, Alec will be ' +b[j]+' years old');
}
}
newS1();
&#13;
答案 1 :(得分:0)
只需循环数据一次,使用索引获取对每个数组中每个对应元素的引用:
let yearsUntil = [2,3,4,5];
let ages = [12,13,14,15];
for (let i = 0; i < ages.length; i += 1) {
let years = yearsUntil[i];
let age = ages[i];
console.log('After ' + years + ' years, Alec will be ' + age + ' years old.');
}
由于数组a
中的每个项都对应于数组b
中的项,因此最好将数据从两个并行数组重构为一个对象数组:
let ageInfo = [
{
yearsUntil: 2,
age: 12
},
{
yearsUntil: 3,
age: 13
},
{
yearsUntil: 4,
age: 14
},
{
yearsUntil: 5,
age: 15
},
];
for (let i = 0; i < ageInfo.length; i += 1) {
console.log('After ' + ageInfo[i].yearsUntil + ' years, Alec will be ' + ageInfo[i].age + ' years old.');
}
或者,由于两者之间存在一致的关系,您可以只存储一个并动态计算另一个:
let ages = [12,13,14,15];
let currentAge = 10;
for (let i = 0; i < ages.length; i += 1) {
console.log('After ' + (ages[i] - currentAge) + ' years, Alec will be ' + ages[i] + ' years old.');
}
如果您正在进行更复杂的计算,您可能希望将其移动到memoized函数中,而不是在循环中进行内联:
let ages = [12,13,14,15];
let currentAge = 10;
let getYearsUntil = (function () {
let cache = {};
return function (age) {
if (cache[age] !== undefined) {
console.log('returning cached age.');
return cache[age];
}
let yearsUntil = age - currentAge;
cache[age] = yearsUntil;
return yearsUntil;
}
}());
for (let i = 0; i < ages.length; i += 1) {
console.log('After ' + getYearsUntil(ages[i]) + ' years, Alec will be ' + ages[i] + ' years old.');
}
// calling getYearsUntil with a previously calculated age
// returns a value from the cache instead of calculating it again.
console.log(getYearsUntil(12));
此示例使用IIFE (Immediately Invoked Function Expression)创建closure,即IIFE返回分配给getYearsUntil
的函数。这允许返回的函数记住它存储在cache
对象中的先前计算。有关记忆的更详细说明,check out this article。