英文:
Set initial value and then make next value as the initial one
问题
我从一个函数将作为字符串的数组值传递给另一个函数
const func1 = () => {
let myArray = ["Harry", "Hermione", "Ron", "Ginny", "Luna"];
myArray.map((arr, i) => func2(arr, i));
}
const func2 = (arrString, index) => {
let before, after;
if (index === 0) {
before = arrString;
after = null;
}
}
func1();
在第一次迭代(index === 0)之后,我希望after等于before的值,当before等于arrString(index = 1)时。我不确定如何循环这个。
期望结果:
before = "Harry",after = null
before = "Hermione",after = "Harry"
before = "Ron",after = "Hermione"
before = "Ginny",after = "Ron"
before = "Luna",after = "Ginny"
before = null,after = "Luna"
英文:
I have values coming from an array as a string from one function to another
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const func1 = () => {
let myArray = ["Harry", "Hermione", "Ron", "Ginny", "Luna"];
myArray.map((arr, i) => func2(arr, i));
}
const func2 = (arrString, index) => {
let before, after;
if (index === 0) {
before = arrString;
after = null;
}
}
func1();
<!-- end snippet -->
After the first iteration(index===0
) I want after = before
value a when and before = arrString(index=1)
. I am not sure how to loop that.
Expected results:
before = "Harry", after = null
before = "Hermione", after = "Harry"
before = "Ron", after = "Hermione"
before = "Ginny", after = "Ron"
before = "Luna", after = "Ginny"
before = null, after = "Luna"
答案1
得分: 1
`map()` 和 `forEach()` 也将正在迭代的数组作为第三个参数传递给回调函数。您可以使用这个参数来访问数组的其他索引。
const func1 = () => {
let myArray = ["Harry", "Hermione", "Ron", "Ginny", "Luna"];
myArray.forEach((elt, i, arr) => func2(elt, i, arr));
}
const func2 = (arrString, index, array) => {
let before = arrString, after;
if (index === 0) {
after = null;
} else {
after = array[index - 1];
}
console.log(`before = ${before} after = ${after}`);
}
func1();
英文:
map()
and forEach()
also pass the array being iterated over as a third argument to the callback function. You can use this to access other indexes of the array.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const func1 = () => {
let myArray = ["Harry", "Hermione", "Ron", "Ginny", "Luna"];
myArray.forEach((elt, i, arr) => func2(elt, i, arr));
}
const func2 = (arrString, index, array) => {
let before = arrString, after;
if (index === 0) {
after = null;
} else {
after = array[index - 1];
}
console.log(`before = ${before} after = ${after}`);
}
func1();
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论