var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }];
说明:
使用 forEach() 方法循环访问该数组,并使用 console.log 输出以下甜甜圈摘要
Jelly donuts cost $1.22 each
Chocolate donuts cost $2.45 each
Cider donuts cost $1.59 each
Boston Cream donuts cost $5.99 each
var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }];
for(var i in donuts){
console.log(`${donuts[i].type} donuts const $${donuts[i].const} each`)
}
您好,是这样子的,不能用for循环,要用foreach()
donuts.forEach(function(value,index,donuts){
console.log(`${donuts[index].type} donuts const $ ${donuts[index].cost} each`)
})
donuts.forEach(function(value,index,donuts){
console.log(`${donuts[index].type} donuts const $ ${donuts[index].cost} each`)
})
这个网上很多例子,你上网比较快,可以直接搜 w3c 菜鸟教程,还可以直接运行代码
$(document).ready(function () {
//这是一个json字符串
var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }];
//$.each(donuts, function (index, obj) {
// console.log(obj.type + " donuts cost$" + obj.cost + " each");
//});
donuts.forEach(function (val, index, arr) {
console.log(val.type + " donuts cost$" + val.cost + " each");
});
});
这我记得是优达学城的一个测试题目吧,,,
是的
for in是循环输出对象属性,循环数组用别的