在Java中,可以使用for循环遍历数组中的对象,如下所示:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
我可以在JavaScript中做同样的事情吗?
在Java中,可以使用for循环遍历数组中的对象,如下所示:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
我可以在JavaScript中做同样的事情吗?
当前回答
在JavaScript中,不建议使用for In循环遍历Array,但最好使用for循环,例如:
for(var i=0, len=myArray.length; i < len; i++){}
它也进行了优化(“缓存”数组长度)。如果你想了解更多,请阅读我关于这个主题的帖子。
其他回答
在JavaScript中,有很多方法可以循环数组。
下面的代码是流行的代码
/**声明输入*/const items=['你好','世界']/**解决方案1。简单适用于*/console.log(解决方案1。简单用于')for(设i=0;i<items.length;i++){console.log(项[i])}console.log()console.log()/**解决方案2。简单的while*/console.log(解决方案2。简单while')设i=0而(i<items.length){console.log(项[i++])}console.log()console.log()/**解决方案3。对于每个*/console.log(解决方案3。“每个”)items.forEach(item=>{console.log(项)})console.log()console.log()/**解决方案4。的*/console.log(解决方案4。对于')for(常量项,共项){console.log(项)}console.log()console.log()
简单的单线解决方案:
arr=[“桌子”,“椅子”];//解决方案arr.map((e)=>{控制台日志(e);返回e;});
在JavaScript中以函数编程方式循环数组的一些用例:
1.只需循环遍历数组
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
注意:严格来说,Array.prototype.forEach()不是一种函数方式,因为它作为输入参数的函数不应该返回值,因此不能将其视为纯函数。
2.检查数组中的任何元素是否通过测试
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3.转换为新阵列
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
注意:map()方法使用对调用数组中的每个元素调用所提供函数的结果创建一个新数组。
4.总结某一特定属性,并计算其平均值
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5.基于原始数组创建新数组,但不进行修改
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6.统计每个类别的数量
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7.基于特定条件检索数组的子集
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
注意:filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
8.对数组进行排序
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9.在数组中查找元素
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
方法返回数组中满足所提供测试函数的第一个元素的值。
工具书类
Array.prototype.some()Array.prototype.forEach()Array.prototype.map()Array.prototype.filter()Array.prototype.sort()Spread语法Array.prototype.find()
深奥的
让a=[“你好”,“世界”];while(a.length){console.log(a.shift());}
性能测试
今天(2022-11-13),我在Chrome 107、Safari 15.2和Firefox 106上对选定的解决方案进行了测试。
结论
解决方案C和D在所有阵列的所有浏览器上都是快速或最快的。解决方案A和B在所有阵列的所有浏览器上都是最慢的
后果
细节
我执行3项测试:
small-用于2元素数组(如OP)-可以在此处运行中等-用于10K元素阵列-您可以在这里运行大-对于100K元素数组-您可以在这里运行
下面的代码段显示了测试中使用的代码。
函数A(A){设r=0;而(a.length)r+=a.shift().length;返回r;}函数B(a){设r=0;对于(i in a)r+=a[i]长度;返回r;}函数C(a){设r=0;对于(a的x)r+=x.length;返回r;}函数D(a){设r=0;对于(i=0;i<a.length;++i)r+=a[i].length;返回r;}函数E(a){设r=0;a.对于每个(x=>r+=x.length);返回r;}let arr=[“你好”,“世界!”];[A,B,C,D,E].forEach(f=>console.log(`${f.name}:${f([…arr])}`))
以下是Chrome对于中等阵列的示例结果:
Opera、Safari、Firefox和Chrome现在都共享一组增强的Array方法来优化许多常见循环。
您可能不需要所有这些,但它们可能非常有用,或者如果每个浏览器都支持它们,它们就会非常有用。
Mozilla实验室发布了他们和WebKit都使用的算法,因此您可以自己添加它们。
筛选器返回满足某个条件或测试的项目数组。
如果每个数组成员都通过测试,则every返回true。
如果有人通过测试,则返回true。
forEach在每个数组成员上运行一个函数,不返回任何内容。
map类似于forEach,但它返回每个元素的操作结果数组。
这些方法都将一个函数作为其第一个参数,并有一个可选的第二个参数,这是一个对象,当数组成员循环通过该函数时,您希望将其范围强加给数组成员。
忽略它,直到你需要它。
indexOf和lastIndexOf查找与其参数完全匹配的第一个或最后一个元素的适当位置。
(function(){
var p, ap= Array.prototype, p2={
filter: function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
},
every: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in this && !fun.call(scope, this[i], i, this))
return false;
++i;
}
return true;
}
return null;
},
forEach: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
fun.call(scope, this[i], i, this);
}
++i;
}
}
return this;
},
indexOf: function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what)
return i;
++i;
}
return -1;
},
lastIndexOf: function(what, i){
var L= this.length;
i= i || L-1;
if(isNaN(i) || i>= L)
i= L-1;
else
if(i< 0) i += L;
while(i> -1){
if(this[i]=== what)
return i;
--i;
}
return -1;
},
map: function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
},
some: function(fun, scope){
var i= 0, L= this.length;
if(typeof fun== 'function'){
while(i<L){
if(i in this && fun.call(scope, this[i], i, this))
return true;
++i;
}
return false;
}
}
}
for(p in p2){
if(!ap[p])
ap[p]= p2[p];
}
return true;
})();