我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
总结:
创建新序列:地图
let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(元素,索引,序列) => {返回元素 * 2; }) console.log(arr); console.log(newArr);
forEach 是一种位于 Array.prototype 的函数,它将作为一个论点采取呼叫回归函数,然后对序列中的每个元素进行此呼叫回归函数,与地图() 函数不同,forEach 函数不会返回任何东西(未定义)。
其他回答
你可以使用:
ForEach theArray.forEach(功能(序列,索引) { console.log(索引); console.log(序列); }; for(var i=0; i<theArray.length; i++) { console.log(i) } 地图 theArray.map(x => console.log(x));地图 theArray.filter(x => console.log(x));
而且还有很多其他人为 iteration。
如果你想使用 forEach(),它会看起来像 -
theArray.forEach ( element => {
console.log(element);
});
如果你想使用(),它会看起来像 -
for(let idx = 0; idx < theArray.length; idx++){
let element = theArray[idx];
console.log(element);
}
总结:
创建新序列:地图
let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(元素,索引,序列) => {返回元素 * 2; }) console.log(arr); console.log(newArr);
forEach 是一种位于 Array.prototype 的函数,它将作为一个论点采取呼叫回归函数,然后对序列中的每个元素进行此呼叫回归函数,与地图() 函数不同,forEach 函数不会返回任何东西(未定义)。
你可以这样打电话给每个人:
forEach 将在您提供的序列上进行 iterate 并为每个 iteration 将有保持该 iteration 的值的元素. 如果您需要索引,您可以通过 i 作为 forEach 的呼叫回复函数中的第二个参数获得当前指数。
Foreach 基本上是一种高顺序函数,它作为其参数需要另一个函数。
let theArray= [1,3,2];
theArray.forEach((element) => {
// Use the element of the array
console.log(element)
}
出口:
1
3
2
你也可以在这样的序列上进行 iterate:
for (let i=0; i<theArray.length; i++) {
console.log(i); // i will have the value of each index
}
最接近您的想法的方式将是使用 Array.forEach() 接受关闭函数,该函数将适用于序列的每个元素。
myArray.forEach(
(item) => {
// Do something
console.log(item);
}
);
另一种可行的方式是使用 Array.map() 以相同的方式工作,但它也需要所有值,你返回并返回它们在一个新的序列(基本上将每个元素地图到一个新的),如下:
var myArray = [1, 2, 3];
myArray = myArray.map(
(item) => {
return item + 1;
}
);
console.log(myArray); // [2, 3, 4]